Skip to content

Conversation

@Mitchellw1233
Copy link

Versions

  • Python 3.12
  • fastapi 0.116.1
  • fastapi-utils 0.8.0

Expected result

As type Annotated is now more or less the default for fastapi, when using dependency: Annotated[Dependency, Depends(get_dep)] as a class attribute in a CBV, i expected it to work also.

Error (actual result)

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class '__main__.Dependency'> is a valid Pydantic field type. If you are using a return type annotation that is not a valid Pydantic field (e.g. Union[Response, dict, None]) you can disable generating the response model from the type annotation with the path operation decorator parameter response_model=None. Read more: https://fastapi.tiangolo.com/tutorial/response-model/

SImple example

from typing import Annotated

from fastapi import APIRouter, Depends, FastAPI

from fastapi_utils.cbv import cbv


class Dependency:    
    def one(self):
        return 1


def get_dep():
    return Dependency()


app = FastAPI()
router = APIRouter()


@cbv(router)
class ItemCBV:
    # Works: `dependency: Dependency = Depends(get_dep)`
    # Does not work:
    dependency: Annotated[Dependency, Depends(get_dep)]

    @router.post("/item")
    def create_item(self):
        return self.dependency.one()


app.include_router(router)

Solution

This simple change solves the problem, as include_extras=True in get_type_hints includes the full Annotated typehint instead of just the type.

See https://docs.python.org/3/library/typing.html for more information about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant