Search code examples
pythonfastapipydanticoptional-parameters

How to exclude Optional unset values from a Pydantic model using FastAPI?


I have this model:

class Text(BaseModel):
    id: str
    text: str = None


class TextsRequest(BaseModel):
    data: list[Text]
    n_processes: Union[int, None]

So I want to be able to take requests like:

{"data": ["id": "1", "text": "The text 1"], "n_processes": 8} 

and

{"data": ["id": "1", "text": "The text 1"]}.

Right now in the second case I get

{'data': [{'id': '1', 'text': 'The text 1'}], 'n_processes': None}

using this code:

app = FastAPI()

@app.post("/make_post/", response_model_exclude_none=True)
async def create_graph(request: TextsRequest):
    input_data = jsonable_encoder(request)

So how can I exclude n_processes here?


Solution

  • Since Pydantic >= 2.0 deprecates model.dict() use model.model_dump(...) instead.

    You can use exclude_none param of Pydantic's model.dict(...):

    class Text(BaseModel):
        id: str
        text: str = None
    
    
    class TextsRequest(BaseModel):
        data: list[Text]
        n_processes: Optional[int]
    
    
    request = TextsRequest(**{"data": [{"id": "1", "text": "The text 1"}]})
    print(request.dict(exclude_none=True))
    

    Output:

    {'data': [{'id': '1', 'text': 'The text 1'}]}
    

    Also, it's more idiomatic to write Optional[int] instead of Union[int, None].