How to Use Field in Pydantic Models with FastAPI
In FastAPI, use
Field from Pydantic to add extra information like default values, descriptions, and validation rules to model fields. Import Field and use it inside your Pydantic model to customize how FastAPI handles input data.Syntax
The Field function is used inside a Pydantic model to define metadata and validation for a field. It accepts parameters like default value, description, example, gt (greater than), lt (less than), and more.
Basic syntax:
from pydantic import BaseModel, Field
class ModelName(BaseModel):
field_name: field_type = Field(default_value, description="Description here", example=value)python
from pydantic import BaseModel, Field class User(BaseModel): name: str = Field(..., description="The user's full name", example="Alice") age: int = Field(18, gt=0, description="User's age, must be positive")
Example
This example shows a FastAPI app using a Pydantic model with Field to add descriptions, default values, and validation. The age field must be greater than 0, and name is required.
python
from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class User(BaseModel): name: str = Field(..., description="The user's full name", example="Alice") age: int = Field(18, gt=0, description="User's age, must be positive", example=30) @app.post("/users/") async def create_user(user: User): return {"message": f"User {user.name} aged {user.age} created."}
Output
POST /users/ with JSON {"name": "Bob", "age": 25} returns {"message": "User Bob aged 25 created."}
Common Pitfalls
- Using
Fieldwithout a default or...(ellipsis) for required fields causes errors. - Setting validation constraints like
gtorlton incompatible types will fail. - Confusing
defaultvalue withdefault_factoryfor dynamic defaults.
Example of a common mistake and fix:
python
from pydantic import BaseModel, Field # Wrong: missing default or ellipsis for required field class ProductWrong(BaseModel): name: str = Field(description="Product name") # This will cause an error # Right: use ellipsis to mark required class ProductRight(BaseModel): name: str = Field(..., description="Product name")
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| default | Default value for the field | Field(10) |
| ... | Marks field as required | Field(...) |
| description | Text shown in docs for the field | Field(..., description="User age") |
| example | Example value shown in docs | Field(..., example=25) |
| gt | Value must be greater than this | Field(..., gt=0) |
| lt | Value must be less than this | Field(..., lt=100) |
| default_factory | Function to generate default value | Field(default_factory=list) |
Key Takeaways
Use Field(...) to mark a Pydantic model field as required in FastAPI.
Add descriptions and examples with Field to improve API docs automatically.
Use validation parameters like gt and lt inside Field to enforce rules.
Remember to provide a default or ellipsis; otherwise, Pydantic raises errors.
Use default_factory for dynamic default values like lists or dicts.