FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

`Annotated` dependencies are interpreted incorrectly when using `PEP 695`-style type alias. · Issue #10719 · fastapi/fastapi · GitHub

Repository navigation

Annotated dependencies are interpreted incorrectly when using PEP 695-style type alias. #10719

Closed

Description

Discussed in #10662

Originally posted by Rockmizu November 16, 2023

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from __future__ import annotations

from typing import Annotated, TypeAlias

from fastapi import Depends, FastAPI

app = FastAPI()


# dependency
async def some_value() -> int:
    return 123

# This works.
DependedValue: TypeAlias = Annotated[int, Depends(some_value)]

# This won't work.
# type DependedValue = Annotated[int, Depends(some_value)]


@app.get('/')
async def get_with_dep(value: DependedValue) -> str:
    print(f'{type(value) = !r}')
    print(f'{value = !r}')

    assert isinstance(value, int), '`value` should be an integer.'
    assert value == 123, '`value` should be 123.'

    return f'value: {value}'

Description

When using the method in line 15:

DependedValue: TypeAlias = Annotated[int, Depends(some_value)]

to declare a type alias, FastAPI correctly interprets it and fills the value with 123 for get_with_dep.

However, when using the new type alias syntax introduced in Python 3.12 (line 18):

type DependedValue = Annotated[int, Depends(some_value)]

FastAPI interprets it as a URL query parameter and responds with HTTP 422 Unprocessable Entity when accessing /.

Expected Response

HTTP 200 OK

"value: 123"

Actual Response

HTTP 422 Unprocessable Entity

{"detail":[{"type":"missing","loc":["query","value"],"msg":"Field required","input":null,"url":"https://errors.pydantic.dev/2.5/v/missing"}]}

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.104.1

Pydantic Version

2.5.1

Python Version

Python 3.12.0

Additional Context

No response

Activity

  1. dev-loki commented on Feb 11, 2024

    Contributor

    I'm in search for my first fastapi contribution and as such I might ask some not so clever questions.

    To this problem:
    Wouldn't this be solved by unacking the typing.TypeAliasType via using it's __value__ attribute?

    This can done before dependencies.utils:328:

        if isinstance(annotation, TypeAliasType):
            annotation = annotation.__value__

    I can work in python<3.12 with something like:

    try:
        from typing import TypeAliasType
    except ImportError:
        TypeAliasType = type("TypeAliasType", tuple(), dict(__value__=None))  # dict content needed?

    (more elegant approach appreciated)

    1. Did I miss someting?
    2. Is this enough to create a PR?
    3. Is it enough when this doesn't break tests or should I add one test?

    Best regards and happy weekend,

    Torsten Zielke

  2. imacat commented on Mar 9, 2024

    Confirm this issue.

    With Python 3.12 new type syntax, FastAPI ignores the dependency annotation.

    from typing import Annotated, TypeAlias
    from fastapi import FastAPI, Query, Depends
    app: FastAPI = FastAPI()
    
    def get_name1(name1: Annotated[str, Query(title="Name")]) -> str:
        return f"Name: {name1}"
    
    def get_name2(name2: Annotated[str, Query(title="Name")]) -> str:
        return f"Name: {name2}"
    
    Name1: TypeAlias = Annotated[str, Depends(get_name1)]
    type Name2 = Annotated[str, Depends(get_name2)]
    
    @app.get("/")
    async def test(name1: Name1, name2: Name2) -> dict[str, str]:
        return {"name1": name1, "name2": name2}
    

    The dependency get_name2 is ignored.

    user@host ~ % curl -X 'GET' 'http://localhost:8000/?name1=betty1&name2=betty2' -H 'accept: application/json'
    {"name1":"Name: betty1","name2":"betty2"}
    user@host ~ %
    
  3. declaresub commented on Apr 30, 2024

    I too keep running into this issue.

  4. Prometheus3375 commented on Nov 26, 2024

    Not just dependencies, any kind of annotations stops working. For example:

    type DateInBody = Annotated[date, Body(embed=True)]
    
    
    @app.post('/api/endpoint')
    async def api_endpoint(
            *,
            my_date: DateInBody,
            ) -> date:
        return date

    /api/endpoint has my_date parameter in request query, not in its body. Removing type before DateInBody definitions solves the issue: my_date parameter is now expected in request body.

  5. jmaillefaud commented on Mar 27, 2025

    For reference, here is the link to the python type documentation on the three modern ways of defining type aliases: https://typing.python.org/en/latest/spec/aliases.html

  6. uriyyo commented on Oct 5, 2025

    Contributor

    For those still waiting for the official FastAPI fix - you can use fastapi-backports until the official release.

    pip install fastapi-backports

    Brings multiple Query models and PEP 695 type alias support to FastAPI until it is officially supported:

    https://github.com/uriyyo/fastapi-backports

    Usage example:

    import fastapi_backports.apply  # noqa: F401
    
    from typing import Annotated, Any
    
    from fastapi import FastAPI, Query
    from pydantic import BaseModel
    
    app = FastAPI()
    
    
    class UserFilters(BaseModel):
        min_age: int | None = None
        max_age: int | None = None
    
    
    class GroupFilters(BaseModel):
        min_size: int | None = None
        max_size: int | None = None
    
    
    type UserFiltersDependency = Annotated[
        UserFilters,
        Query(),
    ]
    
    type GroupFiltersDependency = Annotated[
        GroupFilters,
        Query(),
    ]
    
    
    @app.get("/filters")
    async def get_filters(
        user_filters: UserFiltersDependency,
        group_filters: GroupFiltersDependency,
    ) -> dict[str, Any]:
        return {
            "user_filters": user_filters,
            "group_filters": group_filters,
        }
    GET /filters?min_age=10&max_size=20
    
    {
      "user_filters": {
        "min_age": 10,
        "max_age": null
      },
      "group_filters": {
        "min_size": null,
        "max_size": 20
      }
    }
  7. tiangolo commented on Feb 5, 2026

    Member

    This should be solved by #13920, available in FastAPI 0.128.2, released in the next few hours. 🎉

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionQuestion or problem

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions


      Back | FazBrowse Home | New Git URL