Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
9 tasks done
Kludex opened this issue Nov 26, 2023 Discussed in #10662 · 3 comments · May be fixed by #11140
Open
9 tasks done

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

Kludex opened this issue Nov 26, 2023 Discussed in #10662 · 3 comments · May be fixed by #11140
Labels
question Question or problem

Comments

@Kludex
Copy link
Sponsor Collaborator

Kludex commented Nov 26, 2023

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

@Kludex Kludex added the question Question or problem label Nov 26, 2023
@dev-loki
Copy link

dev-loki commented Feb 11, 2024

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

@dev-loki dev-loki linked a pull request Feb 13, 2024 that will close this issue
@imacat
Copy link

imacat commented 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 ~ %

@declaresub
Copy link

I too keep running into this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants