-
First Check
Commit to Help
Example Codefrom typing import Any, Dict
from fastapi import FastAPI
from pydantic import BaseModel, Field, SerializationInfo, model_serializer
class SomeModel(BaseModel):
lorem: str = Field(..., description="describe me")
ipsum: int
@model_serializer(when_used="always", mode="wrap")
def clean_model(self, serializer: Any, info: SerializationInfo) -> Dict[str, Any]:
data: Dict[str, Any] = serializer(self)
return data
app = FastAPI()
@app.get("/another/{dataset}", response_model=SomeModel)
def get_another_dataset(dataset: str):
raise NotImplementedErrorDescription
Operating SystemLinux, Windows, macOS, Other Operating System DetailsNo response FastAPI Version0.104.1 Pydantic Version2.5.1 Python Version3.9 Additional ContextUncovered while investigating this geojson-pydantic issue. Edit: code sandbox available here. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
|
I'm facing same issue. I think it can be narroved down to Pydantic's model with |
Beta Was this translation helpful? Give feedback.
-
|
I ran into this recently, and I found a workaround. In my case, removing the |
Beta Was this translation helpful? Give feedback.
-
|
The best workaround I have found is to not type hint the return on the serializer. Then it will use the same definition as it would without the serializer defined. def clean_model(self, serializer: Any, info: SerializationInfo): # type: ignore [no-untyped-def]From the FastAPI side of things this is because it calls |
Beta Was this translation helpful? Give feedback.

The best workaround I have found is to not type hint the return on the serializer. Then it will use the same definition as it would without the serializer defined.
From the FastAPI side of things this is because it calls
.model_json_schema(mode="serialization")and typing the return of the serializer changes what pydantic returns for the serialization mode. I feel like what FastAPI is doing is correct and the root of the issue is on the pydantic side. I wrote up an issue on pydantic requesting a nicer way to handle this: pydantic/pydantic#8791 if anyone wants thumbs up it or chime in with…