I need to supply only payload schema for API endpoint without any Pydantic validation (FastAPI==0.110.1, Pydantic v2):
from typing import Literal, Annotated
import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel, Field, RootModel
app = FastAPI()
def get_openapi_extra(model) -> dict:
return {
"requestBody": {
"content": {"application/json": {"schema": model.schema(ref_template="#/components/schemas/{model}")}}
}
}
class Cat(BaseModel):
pet_type: Literal['cat']
meows: int
class Dog(BaseModel):
pet_type: Literal['dog']
barks: float
class Lizard(BaseModel):
pet_type: Literal['reptile', 'lizard']
scales: bool
class Model(RootModel):
root: Annotated[Cat | Dog | Lizard, Field(..., discriminator='pet_type')]
@app.get("/", openapi_extra=get_openapi_extra(Model))
def index():
return "ok"
In Pydantic v1 and FastAPI==0.98.0 it worked without problems. But when I started to upgrade to Pydantic v2 and FastAPI I faced the next problem:
It seems that FastAPI does not know about Lizard, Dog and Cat schemas…
How to fix it?