'FastAPI' object has no attribute 'default_response_class'

Question:

I am trying to include a router in the main FastAPI router:

from fastapi import FastAPI

from test.main.app.google_calendar_wrapper import app as calendar_manager_router

app = FastAPI()

# 
app.include_router(calendar_manager_router, prefix="/calendar_manager", tags=["calendar_manager"])

@app.get("/")
def root():
    return {"message": "Home Page"}

However, when running

uvicorn  test.main.app.webhook.router:app --port 8050 --reload

I get an error:

AttributeError: ‘FastAPI’ object has no attribute ‘default_response_class’

My file structure is:

test
| main
  | app
    |  google_calendar_wrapper
      | endpoints.py
      | __init__.py
    |  webhooks
      |  router.py

So far I have tried:

  • Not including the router, in this case the application starts normally
  • google_calendar_wrapper with and without __init__.py. If with an __init__.py, I tried exporting the google_calendar_wrapper and it still raises the same error
  • Both routers work independently of each other but nothing has helped so far and I have not found any solutions.

Here is the calendar_manager_router definition:

from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def root():
    return {"message": "Hello World"}


@app.get("/health")
def health():
    """Api health endpoint."""
    return {"Api is up and running"}
Asked By: Showertime

||

Answers:

FastAPI’s include_router accepts an APIRouter, but the object you imported in the main file, calendar_manager_router, is another FastAPI object. In your google_calendar_wrapper, you should be defining an APIRouter and that’s what you import and include in your main app.

In google_calendar_wrapper, change it to:

from fastapi import APIRouter

router = APIRouter()  # <---------

@router.get("/")
def root():
    return {"message": "Hello World"}

@router.get("/health")
def health():
    """Api health endpoint."""
    return {"Api is up and running"}

Notice the change to use APIRouter.

Then in your main app:

from test.main.app.google_calendar_wrapper import router as calendar_manager_router

...

app = FastAPI()

app.include_router(
  calendar_manager_router, 
  prefix="/calendar_manager", 
  tags=["calendar_manager"]
)

See the FastAPI tutorials on Bigger Applications – Multiple Files:

You want to have the path operations related to your users separated from the rest of the code, to keep it organized.

But it’s still part of the same FastAPI application/web API (it’s part of the same "Python Package").

You can create the path operations for that module using APIRouter.

You can think of APIRouter as a "mini FastAPI" class.

Answered By: Gino Mempin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.