-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Description
I am currently using pydantic model as below. It has 2 optional fields description and tax.
from typing import Optional
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = Field(None, title="The description of the item", max_length=300)
price: float = Field(..., gt=0, description="The price must be greater than zero")
tax: Optional[float] = None
@app.post("/items/")
async def create_item(item: Item):
return item
Problem - How to exclude optional fields from JSON when not supplied as part of the request.
Request -:
{
"name": "A",
"price": 10.21
}
Fast API produces -:
{
"name": "A",
"description": null,
"price": 10.21,
"tax": null
}
Expected -:
{
"name": "A",
"price": 10.21
}
PYDANTIC provides a way (exclude_none flag) to do that but how to make use of that flag when it is being used in fast API?