mifol68042
mifol68042

Reputation: 321

FastAPI - module 'app.routers.test' has no attribute 'routes'

I am trying to setup an app using FastAPI but keep getting this error which I can't make sense of. My main.py file is as follows:

from fastapi import FastAPI
from app.routers import test

app = FastAPI()
app.include_router(test, prefix="/api/v1/test")

And in my routers/test.py file I have:

from fastapi import APIRouter, File, UploadFile
import app.schemas.myschema as my_schema

router = APIRouter()
Response = my_schema.Response


@router.get("/", response_model=Response)
def process(file: UploadFile = File(...)):
    # Do work

But I keep getting the following error:

File "/Users/Desktop/test-service/venv/lib/python3.8/site-packages/fastapi/routing.py", line 566, in include_router for route in router.routes: AttributeError: module 'app.routers.test' has no attribute 'routes' python-BaseException

I cant make sense of this as I can see something similar being done in the sample app here.

Upvotes: 6

Views: 12418

Answers (3)

Carl
Carl

Reputation: 26

The problem lies in your import statement, your import should be like

from parentfolder.file import attribute

Confused? no worries let me make it simple Any variable you use to define and assign to APIRouter, becomes your attribute. in your example in test.py, you defined routes as your attribute routes = APIRouter() that means that if you want to use it in any other place, you need to do as below

from routers.test import routes

GoodLuck

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23079

I think you want:

app.include_router(test.router, prefix="/api/v1/test")

rather than:

app.include_router(test, prefix="/api/v1/test")

Upvotes: 15

Yagiz Degirmenci
Yagiz Degirmenci

Reputation: 20598

No, you can not directly access it from the app, because when you add an instance of APIRouter with include_router, FastAPI adds every router to the app.routes.

   for route in router.routes:
        if isinstance(route, APIRoute):
            self.add_api_route(
                ...
            )

It does not add the route to the application instead it adds the routes, but since your router is an instance of APIRouter, you can reach the routes from that.

class APIRouter(routing.Router):
    def __init__(
        self,
        routes: Optional[List[routing.BaseRoute]] = None,
        ...
    )

Upvotes: 0

Related Questions