Module 3 — Request Bodies & Pydantic Models
In this module, you’ll learn how to receive JSON bodies in FastAPI using Pydantic models. FastAPI uses Pydantic for data validation and automatic docs generation.
1. Creating a Pydantic Model
A request body must be represented by a Pydantic model.
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str price: float description: str | None = None in_stock: bool = True app = FastAPI()
2. Receiving a Request Body
FastAPI automatically validates incoming JSON.
from fastapi import FastAPI from pydantic import BaseModel class Item(BaseModel): name: str price: float description: str | None = None app = FastAPI() @app.post("/items/") async def create_item(item: Item): return {"message": "Item received", "item": item}
3. Nested Models
Pydantic supports nested models for structured data.
from fastapi import FastAPI from pydantic import BaseModel class Manufacturer(BaseModel): name: str country: str class Product(BaseModel): title: str price: float manufacturer: Manufacturer app = FastAPI() @app.post("/products/") async def create_product(product: Product): return product
4. Model Validation — Automatic Errors
If data is missing or wrong type, FastAPI returns a structured JSON error.
{ "detail": [ { "loc": ["body", "price"], "msg": "field required", "type": "value_error.missing" } ] }
No comments:
Post a Comment