Originally posted by michaeligreenberg March 28, 2023
Here's an example FastAPI app:
from typing import Tuple
from fastapi import FastAPI
from pydantic import BaseModel
class Point(BaseModel):
coordinates: Tuple[float, float]
app = FastAPI()
@app.post("/point")
def create_trip(point: Point):
return {"status": "OK"}
Using datamodel-codegen
with the --use-generic-container-types
option on the response from the app's /openapi.json
endpoint produces the following schema:
from __future__ import annotations
from typing import Optional, Sequence, Union
from pydantic import BaseModel, Field
class Point(BaseModel):
coordinates: Sequence[Union[float, float]] = Field(
..., max_items=2, min_items=2, title='Coordinates'
)
...
Besides the Pydantic v1 problem of unenforced field constraints on a generic, I also noticed that the coordinates field has the repetitive generic type of Sequence[Union[float, float]]
; I believe that just Sequence[float]
would suffice. A possible improvement would be to detect when there is only one possible type and omit the Union.
Details
fastapi 0.95.0
datamodel-codegen 0.17.1
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too