Sometimes you want to send more than one piece of information in the body of a request. FastAPI lets you handle multiple body parameters easily.
Multiple path parameters in FastAPI
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class User(BaseModel): username: str email: str @app.post("/create") async def create_item_user(item: Item, user: User): return {"item": item, "user": user}
Each body parameter must be a Pydantic model or a simple type.
FastAPI automatically reads and validates each parameter from the request body.
item and user. FastAPI reads both from the JSON body.from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class User(BaseModel): username: str email: str @app.post("/create") async def create_item_user(item: Item, user: User): return {"item_name": item.name, "user_email": user.email}
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Product(BaseModel): title: str quantity: int class Customer(BaseModel): name: str phone: str @app.post("/order") async def place_order(product: Product, customer: Customer): return {"product": product.title, "customer": customer.name}
This FastAPI app defines two models: Item and User. The endpoint /create accepts both as body parameters. It returns a message combining their data.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float class User(BaseModel): username: str email: str @app.post("/create") async def create_item_user(item: Item, user: User): return { "message": f"User {user.username} created item {item.name} costing ${item.price}" }
When sending the request, the JSON body must include both parameters as separate JSON objects.
Example request body:
{
"item": {"name": "Book", "price": 12.99},
"user": {"username": "alice", "email": "alice@example.com"}
}
FastAPI uses the parameter names to find the matching keys in the JSON body.
FastAPI lets you accept multiple body parameters by defining them as function arguments with Pydantic models.
Each parameter is read from the JSON body using its name as the key.
This helps organize and validate complex request data easily.