Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI error when using Annotated in Class dependencies

Tags:

python

fastapi

FastAPI added support for Annotated (and started recommending it) in version 0.95.0.

Additionally, FastAPI has a very powerful but intuitive Dependency Injection system (documentation). Moreover, FastAPI support Classes as Dependencies.

However, it seams like Annotated cannot be used in class dependencies, but on function dependencies.

I use FastAPI version 0.110.1.

from __future__ import annotations

from typing import Annotated

from fastapi import FastAPI, Depends, Query

app = FastAPI()


class ClassDependency:
    def __init__(self, name: Annotated[str, Query(description="foo")]):
        self.name = name

async def function_dependency(name: Annotated[str, Query(description="foo")]) -> dict:
    return {"name": name}


@app.get("/")
async def search(c: Annotated[ClassDependency, Depends(function_dependency)]) -> dict:
    return {"c": c.name}

The example above works without errors, but if I replace Depends(function_dependency) with Depends(ClassDependency) an exception is raised with the following message:

pydantic.errors.PydanticUndefinedAnnotation: name 'Query' is not defined

Then, if I remove Annotated from the ClassDependency, by replacing the name: Annotated[str, Query(description="foo")] with the name: str, the example works.

My question: Can I use Class dependencies and put Annotated to the parameters set in the constructor? Because it seams this is not working.

My need: I want to have a class hierarchy for the query params of my api endpoints and provide validation and documentation extras for each of the param.

like image 265
Georgios Syngouroglou Avatar asked Oct 27 '25 12:10

Georgios Syngouroglou


1 Answers

Remove the following and it will work.

from __future__ import annotations
like image 83
Georgios Syngouroglou Avatar answered Oct 29 '25 01:10

Georgios Syngouroglou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!