OpenAPI generation fails with dates with Annotated constraint #11687
-
First Check
Commit to Help
Example Codefrom datetime import date
from typing import Annotated
import annotated_types
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class DataInput(BaseModel):
birthdate: Annotated[
date,
annotated_types.Gt(date(1900, 1, 1)),
annotated_types.Lt(date(2000, 1, 1)),
]
@app.post("/")
def post_root(
data_input: DataInput,
):
return {"birthdate": data_input.birthdate} EDIT: the DescriptionA pydantic ValidationError arises when FastApi calls the openapi utils that generates an instance of fastapi/fastapi/openapi/utils.py Line 530 in a9819df
Note that the concerned fields are indeed defined as optional floats : fastapi/fastapi/openapi/models.py Lines 164 to 167 in a9819df However, FastAPI raises a In the OpenAPi discussion linked above, someone suggests to use custom keywords (A suggested workaround would be to handle the validation myself by adding a pydantic's Operating SystemLinux Operating System DetailsNo response FastAPI Version0.111.0 Pydantic Version2.7.3 Python VersionPython 3.11.5 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 12 replies
-
With from datetime import date, datetime
from typing import Annotated
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/")
def read_root(
data_input: Annotated[date, Query(gt=datetime(1900, 1, 1).timestamp(), lt=datetime(2000, 1, 1).timestamp())]
):
return {"birthdate": data_input} |
Beta Was this translation helpful? Give feedback.
Well if it's a Body param you need to use POST instead of GET. Taking that in mind, you can rewrite the code as