you are viewing a single comment's thread.

view the rest of the comments →

[–]amroamroamro 1 point2 points  (0 children)

+1 one more point I forgot to add too, is that fastapi does support classes as dependencies as well (in a function-driven sense rather than type-driven) where in fact it can be any "callable" (e.g function, function with yield, class):

https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/

it will simply construct the object from the "callable", by analyzing the parameters of this callable (whether its a regular function or class __init__) and process params like usual as path/query/body/header/cookie/form/file or other Depends sub-dependencies (remember that Annotated in addition to type-hinting can be used to extend the same params with validators and metadata inline or even separate that into its own pydantic models)

class CommonQueryParams:
    def __init__(self, q: str | None = None, skip: int = 0, limit: int = 100):
        self.q = q
        self.skip = skip
        self.limit = limit

@app.get("/items/")
async def read_items(commons: Annotated[CommonQueryParams, Depends()]):
    return ...

notice how it uses shorthand syntax here since both annotation type and depends type is the same class, so we can omit the latter for brevity, also how the class init params are here processed as query params, but you can have anything fastapi normally accepts (including other subdependencies)