Skip to content
Advertisement

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

I have this model:

JavaScript

So I want to be able to take requests like:

JavaScript

and

JavaScript

Right now in the second case I get

JavaScript

using this code:

JavaScript

So how can I exclude n_processes here?

Advertisement

Answer

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

JavaScript

Output:

JavaScript

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