Request Body & Pydantic Models in FastAPI

 

So far, we’ve worked with routes, path parameters, and query parameters.But real-world APIs need to send and receive structured data . This is where the request body comes in.FastAPI makes handling request data extremely powerful and simple using Pydantic models.

What is a Request Body?

A request body is data sent by the client (usually in JSON format) to the API.

Example JSON:

{
"name": "Laptop",
"price": 50000
}

What is Pydantic?

Pydantic is a library used by FastAPI for:

  • Data validation
  • Data parsing
  • Type enforcement

It ensures that incoming data is correct and safe.

Creating a Pydantic Model

Let’s define a model for our API:

from pydantic import BaseModel

class Item(BaseModel):
name: str
price: float
in_stock: bool = True

Using Request Body in FastAPI

Now use the model in a POST request:

from fastapi import FastAPI

app = FastAPI()

@app.post("/items/")
def create_item(item: Item):
return {
"name": item.name,
"price": item.price,
"in_stock": item.in_stock
}

How It Works

When a request is sent:

  1. FastAPI reads JSON data
  2. Converts it into a Python object
  3. Validates using Pydantic
  4. Returns response

Automatic Validation Example

If wrong data is sent:

{
"name": "Phone",
"price": "invalid"
}

FastAPI will return an error automatically:

{
"detail": [
{
"loc": ["body", "price"],
"msg": "value is not a valid float"
}
]
}

Optional Fields

You can make fields optional:

from typing import Optional

class Item(BaseModel):
name: str
price: float
description: Optional[str] = None

Nested Models

Pydantic supports nested data:

class Category(BaseModel):
name: str

class Item(BaseModel):
name: str
price: float
category: Category

JSON input:

{
"name": "Book",
"price": 300,
"category": {
"name": "Education"
}
}

List Fields

You can accept lists:

from typing import List

class Item(BaseModel):
name: str
tags: List[str]

Organizing Models (Best Practice)

app/schemas/item.py

from pydantic import BaseModel

class Item(BaseModel):
name: str
price: float

Then import into routes:

from app.schemas.item import Item

Common Mistakes

1. Not using Pydantic models
2. Using plain dictionaries instead of schemas
3. Forgetting type hints
4. Not validating nested data

Key Takeaways

  • Request body is used to send structured data
  • Pydantic ensures automatic validation
  • FastAPI converts JSON → Python objects
  • You can create nested and complex models easily

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling