Skip to content

How to exclude null value from pydantic model used by FAST API #3314

@karan-kumar-by

Description

@karan-kumar-by

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions