Thursday, 20 November 2025

#4 Response Models & Output Validation

FastAPI Module 4 — Response Models & Output Validation

Module 4 — Response Models & Output Validation

FastAPI validates not only incoming data but also outgoing responses. By defining a response_model, you protect your API output from leaking unwanted fields.


1. Basic Response Model

Define a Pydantic model and use it in your endpoint:

from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str price: float app = FastAPI() @app.get("/item", response_model=Item) async def get_item(): return {"name": "Laptop", "price": 45000, "extra": "ignored!"}

Note: The field "extra": "ignored!" is removed in the final output.


2. Controlling Response Fields

Use response_model_exclude and response_model_include when needed.

from fastapi import FastAPI from pydantic import BaseModel class User(BaseModel): username: str email: str is_admin: bool app = FastAPI() @app.get("/public-user", response_model=User, response_model_exclude={"is_admin"}) async def public_user(): return {"username": "john", "email": "john@example.com", "is_admin": True}

3. List Response Models

FastAPI handles lists natively in response models.

from fastapi import FastAPI from pydantic import BaseModel class Product(BaseModel): name: str price: float app = FastAPI() @app.get("/products", response_model=list[Product]) async def get_products(): return [ {"name": "Keyboard", "price": 900}, {"name": "Mouse", "price": 700}, ]

4. Nested Response Models

from fastapi import FastAPI from pydantic import BaseModel class Address(BaseModel): city: str country: str class Customer(BaseModel): name: str address: Address app = FastAPI() @app.get("/customer", response_model=Customer) async def get_customer(): return { "name": "Raghav", "address": {"city": "Chennai", "country": "India"}, }

5. Response Model with Aliases

Use Pydantic aliases to format API output fields.

from fastapi import FastAPI from pydantic import BaseModel, Field class Book(BaseModel): title: str = Field(..., alias="bookTitle") author: str = Field(..., alias="bookAuthor") app = FastAPI() @app.get("/book", response_model=Book) async def get_book(): return {"bookTitle": "FastAPI Guide", "bookAuthor": "John Doe"}

Diagnosis for running all Scripts

 Great — here is the complete ready-to-run folder structure for all 12 FastAPI modules , including: ✅ __init__.py (so Python treats folder...