Working with request bodies (pydantic models)
Working with Request Bodies (Pydantic Models) in FastAPI
🚀 Why Request Bodies Matter in FastAPI
When building APIs with FastAPI, you often need to receive data from users — such as login details, form inputs, or JSON payloads. This data is typically sent as a request body, which FastAPI can automatically read, validate, and convert into Python objects using Pydantic models.
Using Pydantic makes your code cleaner, safer, and easier to maintain — no need to manually parse JSON or check for missing fields.
🧩 What Is a Pydantic Model?
A Pydantic model is a Python class that defines the structure (schema) of your data. It uses type hints to ensure incoming data matches the expected format.
For example, if you expect a user’s name to be a string and their age to be an integer, Pydantic will validate that automatically.
🧱 Example: Handling a Request Body in FastAPI
Let’s create a simple example using FastAPI and Pydantic to receive user information via a POST request.
# Import necessary modules
from fastapi import FastAPI
from pydantic import BaseModel
# Create FastAPI instance
app = FastAPI()
# Define a Pydantic model for request body validation
class User(BaseModel):
  name: str
  email: str
  age: int
# Create a POST endpoint that accepts JSON data
@app.post("/create-user/")
def create_user(user: User):
  This endpoint receives a user object,
  automatically validates it, and returns a response.
  return {
    "message": f"User {user.name} successfully created!",
    "user_data": user
  }
🧠How It Works:
-
The client sends a JSON body like this:
{
 "name": "Sara",
 "email": "sara@example.com",
 "age": 25
}
-
FastAPI reads this request, converts it into a
Userobject, and validates the types.
-
If something is wrong (e.g., missing or wrong type), FastAPI automatically returns a detailed error message.
🧪 Try It Out in FastAPI Docs
Once you run the app (uvicorn main:app --reload), open your browser at:
👉 http://127.0.0.1:8000/docs
You’ll see an interactive Swagger UI where you can send test requests without writing any frontend code.