Skip to content

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

@Kludex

Description

@Kludex

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

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