Use Pydantic models to validate request and response data in FastrAPI
FastrAPI leverages Pydantic models for automatic request validation, type checking, and data serialization. This integration provides type-safe APIs with automatic validation and documentation generation.
Define Pydantic models to validate incoming request data. FastrAPI automatically validates request bodies against your model schemas.
main.py
from pydantic import BaseModelfrom fastrapi import FastrAPIapp = FastrAPI()class User(BaseModel): name: str age: int@app.post("/users")def create_user(user: User): return { "message": f"Created user {user.name}, age {user.age}" }if __name__ == "__main__": app.serve("127.0.0.1", 8080)
FastrAPI automatically validates the request body against the User model. If validation fails, it returns a 422 Unprocessable Entity response with detailed error information.
FastrAPI’s validation process is powered by Rust for maximum performance:
1
Request parsing
The incoming request body is parsed as JSON and converted to Python objects.
2
Model detection
FastrAPI detects Pydantic models in your function signature by checking for model_validate or model_fields attributes (src/pydantic.rs:61-85).
3
Validation
Each Pydantic model validates its corresponding fields from the request body. If validation fails, a 422 response is returned immediately (src/pydantic.rs:34-40).
4
Handler execution
Once all validations pass, the handler function is called with the validated model instances.
FastrAPI uses a “fast path” optimization for routes without Pydantic validation, providing maximum performance when validation isn’t needed. Routes with Pydantic models are still extremely fast due to Rust’s efficient validation handling.
# Fast path: No validation@app.get("/status")def status(): return {"status": "ok"}# Validated path: Still very fast@app.post("/users")def create_user(user: User): return user.dict()
The fast path detection is automatic. FastrAPI analyzes your route handlers at startup to determine the optimal execution path (src/pydantic.rs:170).