Post-parsing middleware / coercing explicit nulls in requests to default values #11457
-
First Check
Commit to Help
Example Code# Basically the model example except that the default for tax is not None
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = Field(default=1.0)
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item DescriptionI have an app which has a number of fields defined as I would like to change all of those to remove the Obviously I can do that with some model validators but it seems like there should be a way to do this without needing to touch each model. Middleware would be an obvious choice but that happens earlier in the request process and what I'd really like would be to have it load as soon as the body has been parsed into a model. I mention the case of explicitly mapping nulls to default values but there are variations on this idea where we have some similar common parameters used across models where the same kind of post-parse middleware would be useful as a standard mechanism rather than something which has to be added to each model. Operating SystemLinux, macOS Operating System DetailsNo response FastAPI Version0.109.2 Pydantic Version2.7.0 Python Version3.12 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
IMO, the easiest way to remove nulls in input data is to implement model_validator for base model and use this base model for all your models:
|
Beta Was this translation helpful? Give feedback.
IMO, the easiest way to remove nulls in input data is to implement model_validator for base model and use this base model for all your models: