FastAPI
Pydantic Request Body
Validate JSON bodies with Pydantic models.
By EZ4Code Team
pydanticrequest-bodyvalidation
Code
from pydantic import BaseModel, Field, EmailStr
from fastapi import FastAPI
app = FastAPI()
class UserIn(BaseModel):
name: str = Field(..., min_length=1, max_length=50)
email: EmailStr
age: int = Field(0, ge=0, le=150)
tags: list[str] = []
@app.post("/users")
def create_user(user: UserIn):
return {"created": user}
@app.put("/users/{user_id}")
def update_user(user_id: int, user: UserIn):
return {"user_id": user_id, "user": user}Explanation
A Pydantic BaseModel declares the shape of the JSON body and FastAPI validates it before the handler runs. Field() adds constraints such as length and numeric bounds, and EmailStr enforces email format. Validation errors automatically produce a 422 response with detailed messages.
More FastAPI Snippets
Path Parameters
Capture typed path segments with validation.
Query Parameters
Parse query strings with defaults and validation.
Dependency Injection
Share logic via Depends and yield-based dependencies.
Response Model
Shape and filter responses with response_model.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.
Async and Await
Define async handlers and run blocking work in a thread.