How to Implement Pagination in FastAPI: Simple Guide
To implement pagination in
FastAPI, use query parameters like page and size to control which items to return. Calculate the start and end indexes based on these parameters and return the sliced data list. This approach helps limit data sent per request and improves performance.Syntax
Use query parameters page and size in your endpoint function to receive pagination inputs. Calculate the start and end indexes for slicing your data list. Return the sliced list as the paginated result.
page: current page number (starts at 1)size: number of items per page- Calculate
start = (page - 1) * sizeandend = start + size - Return
data[start:end]
python
from fastapi import FastAPI, Query from typing import List app = FastAPI() items = [f"item_{i}" for i in range(1, 101)] # Sample data list @app.get("/items/") async def get_items(page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=50)) -> List[str]: start = (page - 1) * size end = start + size return items[start:end]
Example
This example shows a FastAPI endpoint /items/ that returns a paginated list of 100 items. You can request any page and size within limits. For example, /items/?page=2&size=5 returns items 6 to 10.
python
from fastapi import FastAPI, Query from typing import List app = FastAPI() items = [f"item_{i}" for i in range(1, 101)] @app.get("/items/") async def get_items(page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=50)) -> List[str]: start = (page - 1) * size end = start + size return items[start:end]
Output
["item_6", "item_7", "item_8", "item_9", "item_10"]
Common Pitfalls
Common mistakes include:
- Not validating
pageandsizevalues, which can cause errors or unexpected results. - Using zero-based page numbers instead of starting at 1, confusing users.
- Not limiting
size, which can lead to very large responses and slow performance. - Not handling cases where
startindex exceeds data length, which can cause empty results or errors.
python
from fastapi import FastAPI, Query from typing import List app = FastAPI() items = [f"item_{i}" for i in range(1, 101)] # Wrong: no validation, zero-based page @app.get("/bad_items/") async def bad_get_items(page: int = 0, size: int = 10) -> List[str]: start = page * size end = start + size return items[start:end] # Right: validate and start page at 1 @app.get("/good_items/") async def good_get_items(page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=50)) -> List[str]: start = (page - 1) * size end = start + size return items[start:end]
Quick Reference
Tips for FastAPI pagination:
- Use
Queryto validatepageandsizeparameters. - Start
pageat 1 for user-friendly numbering. - Limit
sizeto avoid large responses (e.g., max 50). - Calculate slice indexes as
start = (page - 1) * sizeandend = start + size. - Return sliced data list for the current page.
Key Takeaways
Use query parameters page and size with validation to control pagination in FastAPI.
Calculate start and end indexes to slice your data list correctly for each page.
Always start page numbering at 1 and limit size to prevent large responses.
Validate inputs using FastAPI's Query to avoid errors and unexpected behavior.
Return only the sliced portion of data to improve performance and user experience.