question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dependencies on API Routers not being called for routes via add_route

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from fastapi import APIRouter, Depends, HTTPException
from strawberry.asgi import GraphQL
from . import graphql_schema

def some_func():
	print("CALLED")
	raise HTTPException(status_code=400, detail="X-Token header invalid")

print("HERE")

router = APIRouter(dependencies=[Depends(some_func)])
 
graphql = GraphQL(graphql_schema)
router.add_route("/", graphql)

Description

Accessing a route added with add_route does not invoke the dependencies - it never actually executes some_func (I never see the CALLED print statement in logs)

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.65.2

Python Version

3.9.5

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:5
  • Comments:15 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
ghandiccommented, Oct 2, 2021

This works for me, a little hacky but you need to create a wrapper that takes the request and pulls it back to scope, receive and send.

async def wrapper(req: Request) -> JSONResponse:
    return await graphql(req.scope, req.receive, req._send)

Full example:

from fastapi import FastAPI, HTTPException, APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from strawberry.asgi import GraphQL
import strawberry


@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "Hello World"


schema = strawberry.Schema(query=Query)
graphql = GraphQL(schema)


def some_func():
    print("CALLED")
    raise HTTPException(status_code=400, detail="X-Token header invalid")


async def wrapper(req: Request) -> JSONResponse:
    return await graphql(req.scope, req.receive, req._send)


app = FastAPI()
router = APIRouter(dependencies=[Depends(some_func)])
router.add_api_route(
    "/demo", wrapper, dependencies=router.dependencies, include_in_schema=False, methods=["GET", "POST"]
)

router.add_websocket_route("/demo", graphql)
app.include_router(router)

1reaction
ghandiccommented, Oct 2, 2021

@navyamehta

You can use add_api_route rather than add_route I don’t know if that will cause other issues for you though. When I used add_route I don’t get any docs for the route but using add_api_route I get docs and the deps are managed

add_route is just inherited from starlette so wont get the fastapi magic sprinkled in (eg docs and dependencies)

Full minimal example:

from fastapi import FastAPI, HTTPException, APIRouter, Depends


def some_func():
    print("CALLED")
    raise HTTPException(status_code=400, detail="X-Token header invalid")


async def demo(demo: str):
    return {}


app = FastAPI()
router = APIRouter(dependencies=[Depends(some_func)])
router.add_api_route("/demo", demo)
app.include_router(router)

Read more comments on GitHub >

github_iconTop Results From Across the Web

vue.js - load routes via component from external api and add ...
Another possible solution is to use $router.addRoutes() method. But it is inadequate for your needs. It will not work considering authorization ...
Read more >
Bigger Applications - Multiple Files - FastAPI
All the same parameters , responses , dependencies , tags , etc. Tip. In this example, the variable is called router , but...
Read more >
Routing in ASP.NET Core - Microsoft Learn
Routing is responsible for matching incoming HTTP requests and dispatching those requests to the app's executable endpoints.
Read more >
Routing - Laravel - The PHP Framework For Web Artisans
Middleware; Controllers; Subdomain Routing; Route Prefixes; Route Name Prefixes ... the /api URI prefix is automatically applied so you do not need to ......
Read more >
Create Maintainable Minimal Web APIs - CODE Magazine
A single public method, AddRoutes() , is needed in order to initialize the routes for router class. This method is called from the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found