0
0
FastAPIframework~5 mins

Bulk operations in FastAPI

Choose your learning style9 modes available
Introduction

Bulk operations let you handle many items at once. This saves time and makes your app faster.

When you want to add many records to a database in one go.
When you need to update multiple items with one request.
When deleting several entries at the same time.
When processing a list of data from a user or file upload.
When you want to reduce the number of server calls for efficiency.
Syntax
FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

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

@app.post("/items/bulk")
async def create_items(items: List[Item]):
    # process list of items
    return {"count": len(items), "items": items}

Use List[YourModel] to accept multiple items in the request body.

FastAPI automatically parses the JSON array into Python list of models.

Examples
This endpoint accepts many users at once and returns how many were added.
FastAPI
from typing import List

@app.post("/users/bulk")
async def add_users(users: List[User]):
    return {"added": len(users)}
Use PUT with a list to update multiple products in one request.
FastAPI
from pydantic import BaseModel

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

@app.put("/products/bulk")
async def update_products(products: List[Product]):
    return {"updated": len(products)}
Sample Program

This FastAPI app lets you send many items in one request. It saves them in a list and returns all saved items.

FastAPI
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

app = FastAPI()

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

items_db = []

@app.post("/items/bulk")
async def create_items(items: List[Item]):
    for item in items:
        items_db.append(item)
    return {"message": f"Added {len(items)} items.", "items": items_db}
OutputSuccess
Important Notes

Make sure your client sends a JSON array for bulk operations.

Validate each item with Pydantic models to catch errors early.

Bulk operations reduce network overhead by combining many actions into one.

Summary

Bulk operations handle many items in one request.

Use List[Model] in FastAPI to accept multiple objects.

This improves speed and reduces server calls.