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}'
However, when using the new type alias syntax introduced in Python 3.12 (line 18):
FastAPI interprets it as a URL query parameter and responds with HTTP 422 Unprocessable Entity when accessing /.
{"detail":[{"type":"missing","loc":["query","value"],"msg":"Field required","input":null,"url":"https://errors.pydantic.dev/2.5/v/missing"}]}
Discussed in #10662
Originally posted by Rockmizu November 16, 2023
First Check
Commit to Help
Example Code
Description
When using the method in line 15:
to declare a type alias, FastAPI correctly interprets it and fills the
valuewith123forget_with_dep.However, when using the new type alias syntax introduced in Python 3.12 (line 18):
FastAPI interprets it as a URL query parameter and responds with HTTP 422 Unprocessable Entity when accessing
/.Expected Response
HTTP 200 OK
Actual Response
HTTP 422 Unprocessable Entity
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