fastapi: Dependencies on API Routers not being called for routes via add_route

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

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 5
  • Comments: 15 (5 by maintainers)

Most upvoted comments

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)

@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)

The issue is that we are using add_route I believe, instead of decorating a function with router.get.