0
0
FastAPIframework~5 mins

Field types and constraints in FastAPI

Choose your learning style9 modes available
Introduction

Field types and constraints help you control what kind of data your app accepts. They make sure the data fits rules you set, like length or value limits.

When you want to accept user input but need to check it is the right type, like a number or text.
When you want to limit values, for example, a password must be at least 8 characters.
When you want to make some fields required and others optional.
When you want to add descriptions or examples for your API documentation.
When you want to validate data automatically before using it in your app.
Syntax
FastAPI
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str = Field(..., min_length=3, max_length=50, description="Name of the item")
    price: float = Field(..., gt=0, description="Price must be greater than zero")
    tags: list[str] = Field(default_factory=list, description="List of tags")

Use Field() to add rules like minimum length or greater than checks.

The ... means the field is required.

Examples
This example requires a username between 4 and 20 characters and an age between 18 and 100.
FastAPI
from pydantic import BaseModel, Field

class User(BaseModel):
    username: str = Field(..., min_length=4, max_length=20)
    age: int = Field(..., ge=18, le=100)
Here, price must be greater than zero, and description is optional but limited to 300 characters.
FastAPI
from pydantic import BaseModel, Field

class Product(BaseModel):
    name: str
    price: float = Field(gt=0)
    description: str | None = Field(default=None, max_length=300)
Title must be at least 5 characters. Published defaults to false if not given.
FastAPI
from pydantic import BaseModel, Field

class BlogPost(BaseModel):
    title: str = Field(..., min_length=5)
    content: str
    published: bool = Field(default=False)
Sample Program

This FastAPI app defines an Item model with rules on name length and price value. The POST endpoint accepts an item and returns its data.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Item(BaseModel):
    name: str = Field(..., min_length=3, max_length=50, description="Name of the item")
    price: float = Field(..., gt=0, description="Price must be greater than zero")
    tags: list[str] = Field(default_factory=list, description="List of tags")

@app.post("/items/")
async def create_item(item: Item):
    return {"item_name": item.name, "item_price": item.price, "item_tags": item.tags}
OutputSuccess
Important Notes

Constraints like min_length, max_length, gt (greater than), and ge (greater or equal) help validate data easily.

Use default_factory=list to set an empty list as default to avoid mutable default arguments issues.

Descriptions in Field() help generate clear API docs automatically.

Summary

Field types and constraints ensure your app gets the right kind of data.

You can require fields, limit their size or value, and provide helpful descriptions.

FastAPI uses Pydantic models with Field() to make validation simple and automatic.