30 Mins

3. Pydantic Request Validation

Creating Pydantic Models for Request Validation

Pydantic is the core library for data validation in FastAPI. By defining a Python class that inherits from BaseModel, you enforce type hints on your incoming request data. When a client sends a JSON payload to your endpoint, FastAPI automatically parses, validates, and casts the data into your model schema.

If the input data does not conform to your model definition (e.g., sending a string when an integer is expected), Pydantic raises a validation error, and FastAPI automatically returns a 422 Unprocessable Entity response, saving you from writing manual boilerplate validation logic.

Operator Note: Always declare types explicitly. Pydantic leverages Python's internal type system to perform runtime validation.
Python 3
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class PredictionRequest(BaseModel):
    feature_id: int
    model_name: str
    confidence: float

@app.post('/predict')
def predict(data: PredictionRequest):
    return {'status': 'received', 'received_data': data.dict()}

Handling Null Values, Data Conversions, and Errors

Pydantic allows for fine-grained control over optional fields and type coercion. You can use Optional from the typing module to indicate that a field can be null. If a field is not provided, Pydantic will assign it the default value.

Data coercion is a powerful feature: Pydantic will attempt to convert types whenever possible. For example, if an API client sends the string 10 for an integer field, Pydantic will automatically convert it to the integer 10. If the conversion is impossible, a validation error is triggered.

Operator Note: Use the Field class to add constraints like ge (greater than or equal to) or le (less than or equal to) directly within the model.
Python 3
from pydantic import BaseModel, Field
from typing import Optional

class DataPayload(BaseModel):
    sample_id: int
    tag: Optional[str] = None
    threshold: float = Field(default=0.5)

# Simulating Pydantic parsing
payload = DataPayload(sample_id='100')
print(f'Parsed: {payload.sample_id} (Type: {type(payload.sample_id)}), Tag: {payload.tag}')

Structuring Nested Schemas

For complex data structures, such as batch processing or multi-row predictions, Pydantic supports nested models. You can define child models and use them as types for list fields or dictionary values. This ensures that every element within a batch input adheres to the same schema as a single-item request.

This approach creates a hierarchical validation tree, ensuring that complex JSON bodies are validated at every level of depth.

Operator Note: Nested models are automatically serialized and documented, allowing users to see the full expected structure of the batch request in the Swagger UI.
Python 3
from typing import List
from pydantic import BaseModel

class Observation(BaseModel):
    metric_name: str
    value: float

class BatchPrediction(BaseModel):
    batch_id: str
    observations: List[Observation]

batch = BatchPrediction(batch_id='B01', observations=[{'metric_name': 'accuracy', 'value': 0.95}])
print(batch.json())

Swagger API Documentation

FastAPI automatically extracts metadata from your Pydantic models to generate interactive API documentation using Swagger UI. By simply defining your models, your API documentation is kept in sync with your code, providing a 'Try it out' interface for testers and developers.

You can enhance this documentation by adding descriptions and examples to your Pydantic fields, which then appear in the auto-generated specification.

Operator Note: Navigate to the '/docs' route of your running FastAPI application to see the generated Swagger documentation.
Text
from pydantic import BaseModel, Field

class DocumentationExample(BaseModel):
    name: str = Field(..., description='Name of the algorithm', example='RandomForest')
    version: int = Field(1, description='Model version', example=2)

# FastAPI displays this metadata in /docs

Knowledge Check

Ready to test your understanding of 3. Pydantic Request Validation?

Back