Field validation rules help check if the data sent to your API is correct and safe. They stop wrong or missing information before it causes problems.
Field validation rules in FastAPI
from pydantic import BaseModel, Field class User(BaseModel): name: str = Field(..., min_length=2, max_length=50) age: int = Field(..., ge=1, le=120) email: str = Field(..., regex=r"^[\w\.-]+@[\w\.-]+\.\w{2,4}$")
Field(...) means the field is required.
You can add rules like min_length, max_length, ge (greater or equal), le (less or equal), and regex for patterns.
from pydantic import BaseModel, Field class Product(BaseModel): title: str = Field(..., min_length=3) price: float = Field(..., gt=0)
from pydantic import BaseModel, Field class User(BaseModel): username: str = Field(..., regex=r"^[a-zA-Z0-9_]+$") bio: str | None = Field(None, max_length=200)
This FastAPI app defines a User model with validation rules. When you send data to /users/, FastAPI checks the rules. If data is wrong, it returns clear errors. If data is good, it confirms user creation.
from fastapi import FastAPI from pydantic import BaseModel, Field from fastapi.responses import JSONResponse from fastapi.requests import Request from fastapi.exception_handlers import RequestValidationError app = FastAPI() class User(BaseModel): name: str = Field(..., min_length=2, max_length=50) age: int = Field(..., ge=1, le=120) email: str = Field(..., regex=r"^[\w\.-]+@[\w\.-]+\.\w{2,4}$") @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): return JSONResponse( status_code=422, content={"detail": exc.errors(), "body": exc.body}, ) @app.post("/users/") async def create_user(user: User): return {"message": f"User {user.name} created successfully!", "user": user.dict()}
Validation errors automatically return a 422 status with details.
Use Field(...) to make a field required, or Field(None) to make it optional.
Regex patterns must be raw strings (prefix with r) to avoid escape issues.
Field validation rules check data before your API uses it.
Use Field with options like min_length, max_length, ge, le, and regex.
FastAPI and Pydantic handle errors and give clear messages automatically.
Practice
Field with parameters like min_length or ge in FastAPI models?Solution
Step 1: Understand Field usage in FastAPI
Field is used to define extra validation rules on model fields.Step 2: Recognize validation purpose
Parameters like min_length or ge ensure input data meets conditions before API logic runs.Final Answer:
To validate and restrict input data before processing -> Option AQuick Check:
Field validation = Input data check [OK]
- Confusing validation with output formatting
- Thinking Field creates database tables
- Assuming Field controls routing
Field?Solution
Step 1: Recall correct parameter name for minimum length
FastAPI usesmin_lengthto set minimum string length.Step 2: Match option with correct syntax
name: str = Field(min_length=3) usesmin_length=3, which is correct syntax.Final Answer:
name: str = Field(min_length=3) -> Option BQuick Check:
min_length = min_length [OK]
- Using incorrect parameter names like min or length_min
- Confusing min_length with min for numbers
- Misspelling parameter names
from pydantic import BaseModel, Field
class User(BaseModel):
age: int = Field(ge=18, le=65)
user = User(age=70)What will happen when creating
user?Solution
Step 1: Understand ge and le constraints
ge=18 means age must be >=18, le=65 means age must be <=65.Step 2: Check provided age value
Age 70 is greater than 65, violating the le constraint.Step 3: FastAPI/Pydantic behavior on violation
It raises a validation error when constraints are not met.Final Answer:
An error is raised because age is greater than 65 -> Option AQuick Check:
ge/le constraints cause error if violated [OK]
- Assuming values auto-correct to limits
- Thinking invalid values are ignored
- Confusing ge/le with min_length/max_length
from pydantic import BaseModel, Field
class Product(BaseModel):
code: str = Field(regex="[A-Z]{3}[0-9]{4}")
product = Product(code="abC1234")Solution
Step 1: Analyze regex pattern
Pattern requires exactly 3 uppercase letters followed by 4 digits.Step 2: Check input against pattern
Input "abC1234" has lowercase letters and does not fully match pattern.Step 3: Understand validation result
Regex is case-sensitive by default, so input fails validation causing error.Final Answer:
The regex pattern is case-sensitive and input does not match -> Option CQuick Check:
Regex is case-sensitive unless flagged [OK]
- Assuming regex ignores case without flags
- Thinking Field does not accept regex
- Confusing data types for fields
Field validation is correct?Solution
Step 1: Check length constraints
min_length=5 and max_length=10 ensure username length between 5 and 10.Step 2: Analyze regex pattern
Regex '^[a-zA-Z][a-zA-Z0-9]*$' means username starts with a letter, followed by letters or digits.Step 3: Verify other options
Options starting with a digit are incorrect. Options using regex '^[a-zA-Z0-9]{5,10}$' allow starting with digits. Options using '^[a-zA-Z]{5,10}$' exclude digits.Final Answer:
username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z][a-zA-Z0-9]*$') -> Option DQuick Check:
Start letter + length + allowed chars = username: str = Field(min_length=5, max_length=10, regex='^[a-zA-Z][a-zA-Z0-9]*$') [OK]
- Allowing username to start with digit
- Not enforcing length limits
- Using regex that excludes digits or letters incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
