0
0
FastapiHow-ToBeginner · 3 min read

How to Set Default Values in Pydantic Models in FastAPI

In FastAPI, you set default values in Pydantic models by assigning them directly in the model's field definitions using field_name: type = default_value. This way, if the client omits that field in the request, FastAPI uses the default automatically.
📐

Syntax

To set a default value in a Pydantic model, assign the value directly to the field in the class definition. The syntax is:

field_name: type = default_value

Here:

  • field_name is the name of the data field.
  • type is the expected data type (e.g., str, int).
  • default_value is the value used if none is provided.

This tells Pydantic and FastAPI to use the default if the client does not send this field.

python
from pydantic import BaseModel

class Item(BaseModel):
    name: str = "Default Name"
    price: float = 9.99
    in_stock: bool = True
💻

Example

This example shows a FastAPI app with a Pydantic model that has default values. When you send a POST request without some fields, the defaults are used automatically.

python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str = "Default Name"
    price: float = 9.99
    in_stock: bool = True

@app.post("/items/")
async def create_item(item: Item):
    return item
Output
POST /items/ with body {"price": 15.5} Response: { "name": "Default Name", "price": 15.5, "in_stock": true }
⚠️

Common Pitfalls

Common mistakes when setting default values include:

  • Not assigning a default value, which makes the field required.
  • Using mutable default values like lists or dicts directly, which can cause shared state issues.
  • Confusing None as a default without making the field optional.

Always assign immutable default values or use Field(default_factory=...) for mutable defaults.

python
from pydantic import BaseModel, Field

# Wrong: mutable default shared across instances
class WrongModel(BaseModel):
    tags: list[str] = []  # Avoid this

# Right: use default_factory for mutable defaults
class RightModel(BaseModel):
    tags: list[str] = Field(default_factory=list)
📊

Quick Reference

ConceptExampleNotes
Set default valuename: str = "John"Field is optional, uses default if missing
Optional field with Noneage: int | None = NoneField can be omitted or null
Mutable defaulttags: list[str] = Field(default_factory=list)Avoid shared mutable defaults
Required fieldprice: floatNo default means client must provide value

Key Takeaways

Assign default values directly in Pydantic model fields to make them optional in FastAPI.
Use Field with default_factory for mutable default values like lists or dicts.
Omitting a field with a default in the request uses the default automatically.
Fields without defaults are required and must be provided by the client.
Use Optional types with None defaults to allow null or missing values.