`Annotated` dependencies are interpreted incorrectly when using `PEP 695`-style type alias.
Kludex opened this issue · 3 comments
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
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)
- Did I miss someting?
- Is this enough to create a PR?
- Is it enough when this doesn't break tests or should I add one test?
Best regards and happy weekend,
Torsten Zielke
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 ~ %
I too keep running into this issue.