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

Get the StringConstraints directly from the Identifier type #10322

Open
baderdean opened this issue Sep 25, 2023 · 3 comments
Open

Get the StringConstraints directly from the Identifier type #10322

baderdean opened this issue Sep 25, 2023 · 3 comments
Labels
confirmed feature New feature or request

Comments

@baderdean
Copy link

baderdean commented Sep 25, 2023

Problem:
FastAPI does not validate custom string build using Annotated[str, StringConstraints(...)]

Temporary solution
My solution is to annotate the constrained type with Path again, then it seems to work:

from typing import Annotated

from fastapi import FastAPI, Path
from pydantic import StringConstraints

# In my case this is imported from a lib with pydantic but without fastapi,
# so it can't be changed to Annotated[str, Path(pattern=r"^[a-fA-F0-9]+$")]
Identifier = Annotated[str, StringConstraints(pattern=r"^[a-fA-F0-9]+$")]


app = FastAPI()


@app.get("/{some_id}")
async def get_something(some_id: Annotated[Identifier, Path()]):
    return some_id

Feature request
Would be nice if fastapi would be able to get the constraint directly from the Identifier type without being required to add Annotated[Identifier, Path()].

Originally posted by @JasperJuergensen in #10105 (comment)

@Kludex Kludex added the feature New feature or request label Sep 26, 2023
@Kludex
Copy link
Member

Kludex commented Sep 26, 2023

What the OP wants is this:

from typing import Annotated

from fastapi import FastAPI, Path
from pydantic import StringConstraints

Identifier = Annotated[str, StringConstraints(pattern=r"^[a-fA-F0-9]+$")]

app = FastAPI()

@app.get("/{some_id}")
async def get_something(some_id: Identifier):
    return some_id

A similar feature request is to use pydantic.Field.

@Dragon-GCS
Copy link

It is because missing the matadata when none of Annotated args is FieldInfo or Depends
I've commit a fix pr #10356 . Hope it's work

@ramnes
Copy link

ramnes commented Nov 9, 2023

Isn't it pretty much the same as #10259 and #10109?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
confirmed feature New feature or request
Projects
None yet
Development

No branches or pull requests

4 participants