0
0
FastAPIframework~5 mins

Optional and nullable fields in FastAPI

Choose your learning style9 modes available
Introduction

Optional and nullable fields let you accept data that might be missing or empty. This helps your app handle flexible inputs without errors.

When a user can skip filling a form field.
When an API accepts data that may or may not include certain details.
When you want to allow a field to be empty or set to null explicitly.
When you want to provide default values if data is missing.
When you want to validate data that can be either a value or None.
Syntax
FastAPI
from typing import Optional
from pydantic import BaseModel

class MyModel(BaseModel):
    optional_field: Optional[str] = None  # Field can be missing or None
    nullable_field: str | None = None      # Field can be present but can be None

Optional means the field can be missing or set to None.

Nullable means the field can be present but set to None.

Examples
This model allows nickname to be missing or None.
FastAPI
from typing import Optional
from pydantic import BaseModel

class User(BaseModel):
    name: str
    nickname: Optional[str] = None  # User may or may not provide a nickname
This uses Python 3.10+ syntax for nullable field.
FastAPI
from pydantic import BaseModel

class Product(BaseModel):
    description: str | None = None  # Description can be null or a string
Without a default, the field is required but can be None.
FastAPI
from typing import Optional
from pydantic import BaseModel

class Item(BaseModel):
    price: Optional[float]  # Price is required but can be None, no default given
Sample Program

This FastAPI app defines a User model with optional and nullable fields. When you send a POST request to /users/ with JSON data, it returns the username and shows default messages if bio or website are missing or null.

FastAPI
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    username: str
    bio: Optional[str] = None  # Optional field
    website: str | None = None  # Nullable field

@app.post('/users/')
async def create_user(user: User):
    return {
        'username': user.username,
        'bio': user.bio or 'No bio provided',
        'website': user.website or 'No website provided'
    }
OutputSuccess
Important Notes

Use Optional when a field can be missing or None.

Use str | None (Python 3.10+) to allow null values explicitly.

Setting a default to None makes the field optional in FastAPI.

Summary

Optional fields can be missing or None.

Nullable fields can be present but set to None.

Use these to make your API flexible and user-friendly.