Skip to content
Advertisement

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?

Advertisement

Answer

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].

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement