[Python] fastapi how to modularize code into multiple files with access to app decorators

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I want to distribute my FastAPI code into multiple files so as to make it clear for team, so instead of using decorator i tried using APIRoute , but in this way I can't use FastAPI decorator in other file. Lets say I have my main.py like this

    ... import statements

    rts = [
    APIRoute("/{value}", methods=["get"], endpoint=read_item)
    ]

    app = FastAPI(routes=rts)

    uvicorn.run("main:app", host="0.0.0.0", port=80)


    now I have defined read_item method in another file named read_item.py which i am importing in my main file.

    def read_item(value: int | float = None):
    results = {"value": value}
    return results


    if i start using @app decorator in main file , it will become too large. now the problem is that i can not access app decorators like @app.on_event in read_items.py file as app is declared in main file and method needs to declared in read_item file. is there any way around this in FastAPI ?

    Continue reading...

Compartilhe esta Página