0
0
FastapiHow-ToBeginner · 4 min read

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 Field without a default or ... (ellipsis) for required fields causes errors.
  • Setting validation constraints like gt or lt on incompatible types will fail.
  • Confusing default value with default_factory for 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

ParameterDescriptionExample
defaultDefault value for the fieldField(10)
...Marks field as requiredField(...)
descriptionText shown in docs for the fieldField(..., description="User age")
exampleExample value shown in docsField(..., example=25)
gtValue must be greater than thisField(..., gt=0)
ltValue must be less than thisField(..., lt=100)
default_factoryFunction to generate default valueField(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.