0
0
FastAPIframework~5 mins

Request body declaration in FastAPI

Choose your learning style9 modes available
Introduction

We use request body declaration to tell FastAPI what data to expect from a client when they send information to our server. This helps us get the data in a clear and organized way.

When a user submits a form with details like name and email.
When an app sends data to create a new item in a database.
When you want to receive JSON data from a client in an API call.
When you need to validate the data sent by a client before using it.
When building APIs that accept complex data structures from users.
Syntax
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

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

@app.post("/items/")
async def create_item(item: Item):
    return item

Use a BaseModel class to define the shape of the data you expect.

Declare the request body by adding a parameter with the model type in your path operation function.

Examples
This example shows a user sending their username and age in the request body.
FastAPI
from pydantic import BaseModel

class User(BaseModel):
    username: str
    age: int

@app.post("/users/")
async def create_user(user: User):
    return user
Here, the request body expects a product with an id and description.
FastAPI
from pydantic import BaseModel

class Product(BaseModel):
    id: int
    description: str

@app.post("/products/")
async def add_product(product: Product):
    return product
Sample Program

This program defines a Book model with title and author. When a client sends a POST request with this data, the server responds with a confirmation message.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Book(BaseModel):
    title: str
    author: str

@app.post("/books/")
async def create_book(book: Book):
    return {"message": f"Book '{book.title}' by {book.author} created."}
OutputSuccess
Important Notes

FastAPI automatically converts JSON request bodies into your model objects.

If the client sends wrong or missing data, FastAPI returns an error explaining what is wrong.

Use BaseModel to add validation and clear data structure.

Summary

Request body declaration tells FastAPI what data to expect from clients.

Use Pydantic models (BaseModel) to define the data shape.

FastAPI handles data parsing and validation automatically.