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.
Field types and constraints in 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.
from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(..., min_length=4, max_length=20) age: int = Field(..., ge=18, le=100)
from pydantic import BaseModel, Field class Product(BaseModel): name: str price: float = Field(gt=0) description: str | None = Field(default=None, max_length=300)
from pydantic import BaseModel, Field class BlogPost(BaseModel): title: str = Field(..., min_length=5) content: str published: bool = Field(default=False)
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.
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}
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.
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.
Practice
Field() in a Pydantic model?Solution
Step 1: Understand the role of Pydantic models in FastAPI
Pydantic models define the data structure and validation for request and response data.Step 2: Identify what
Field()addsField()allows adding constraints like min/max length, default values, and descriptions to model fields.Final Answer:
To add validation rules and metadata to model fields -> Option CQuick Check:
Field() = validation and metadata [OK]
- Thinking Field() creates routes or handles requests
- Confusing Field() with database table creation
- Assuming Field() is for HTTP methods
Field()?Solution
Step 1: Recall the correct parameter for minimum length in Field()
The correct parameter to set minimum string length ismin_length.Step 2: Check each option for correct syntax
name: str = Field(min_length=3) usesmin_length=3, which is correct. Others use invalid or incorrect parameters.Final Answer:
name: str = Field(min_length=3) -> Option DQuick Check:
Minimum string length uses min_length [OK]
- Using min instead of min_length for strings
- Using length instead of min_length
- Adding required=True which is not a Field() parameter
from pydantic import BaseModel, Field
class Item(BaseModel):
price: float = Field(gt=0)
name: str = Field(min_length=2, max_length=10)
What happens if you create
Item(price=-5, name='A')?Solution
Step 1: Check the constraints on price
Price must be greater than 0 (gt=0). Given price is -5, which fails this.Step 2: Check the constraints on name
Name must have length between 2 and 10. Given name is 'A' (length 1), which fails min_length=2.Final Answer:
Validation error because price is not greater than 0 and name is too short -> Option AQuick Check:
Both price and name fail constraints [OK]
- Assuming only one field causes error
- Ignoring min_length constraint on strings
- Thinking negative price passes gt=0
from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(min_length=18)
Solution
Step 1: Understand Field constraints for int type
Integer fields usegtorgefor minimum value, notmin_length.Step 2: Identify the error in the code
Usingmin_lengthon an int field causes a validation error because it applies only to strings or collections.Final Answer:
min_length is invalid for integer fields -> Option BQuick Check:
min_length applies to strings, not ints [OK]
- Using string constraints on numeric fields
- Thinking Field() can't be used with int
- Confusing default value requirement
tags field that must be a list of strings, each string at least 2 characters long. Which is the best way to enforce this using Pydantic Field()?Solution
Step 1: Understand the requirement for list of strings with string length constraints
We need to enforce each string in the list to have at least 2 characters.Step 2: Identify how to apply constraints on list items
Pydantic'sconstrcan constrain strings, andconlistcan constrain lists of constrained types.Step 3: Evaluate options
from typing import List from pydantic import BaseModel, Field, conlist, constr class Product(BaseModel): tags: conlist(constr(min_length=2)) usesconlist(constr(min_length=2))which correctly enforces each string's min length inside the list. Others either apply min_length to the list itself or incorrectly.Final Answer:
Use conlist with constr to enforce string length inside list -> Option AQuick Check:
conlist(constr(min_length=2)) = correct nested constraints [OK]
- Applying min_length to the list instead of strings inside
- Not using constr for string constraints
- Confusing min_items with min_length
Ready to prove it?
Pass the test and this pattern moves unknown
