pythonfastapipydantic

Is there a best practice for defining optional fields in Pydantic models?


I'm working with Pydantic for data validation in a Python project and I'm encountering an issue with specifying optional fields in my BaseModel.

from pydantic import BaseModel

class MyModel(BaseModel):
    author_id: int | None    # Case 1: throws error
    author_id: Optional[int] # Case 2: throws error
    author_id: int = None    # Case 3: works

Now, while requesting an endpoint that accepts the above model as its JSON body, I am not providing the field author_id in the request.

When I use author_id: int | None, I get an error saying that a required field is missing. However, if I change it to author_id: Optional[int], I encounter the same error. But when I use author_id: int = None or author_id: Optional[int] = None, the model works as expected without errors. (Working if = is present)

Do you have any recommendations on how to properly define optional fields in Pydantic models? Is there a specific version of Pydantic (or another library) that supports the int | None syntax correctly?


Solution

  • The reason you encounter an error is that there is no default value. The annotations don't actually do anything by themselves.

    All of the options bellow work, and they are pretty much equivalent under the hood. The third option is now recommended for projects only using Python 3.10+

    from pydantic import BaseModel
    
    class MyModel(BaseModel):
        author_id: Optional[int] = None # the original way
        author_id: Union[int, None] = None # another option
        author_id: int | None = None # more modern option (Python 3.10+)