FastAPI Pagination
fastapi-pagination is a Python library designed to simplify pagination in FastAPI applications. It provides utility functions and data models to paginate database queries and return paginated responses, supporting various strategies like page-based, limit-offset, and cursor-based pagination. The library is actively maintained, with frequent minor releases, and is currently at version 0.15.12.
Warnings
- deprecated Several database extensions have been deprecated in version 0.15.7, including `bunnet`, `databases`, `gino`, `odmantic`, and `orm`. Users should migrate to actively maintained extensions like `sqlalchemy`, `sqlmodel`, or `beanie` if possible.
- breaking The `paginate` function for async operations will be removed in a future major version. The dedicated `apaginate` function should be used for async calls to ensure forward compatibility.
- gotcha Using the default `paginate` function (i.e., `from fastapi_pagination import paginate`) on database queries will load all data into memory before paginating, leading to performance issues and high memory consumption for large datasets.
- breaking In version 0.13.x, the `Page.create` class method signature changed; the `total` argument is now keyword-only.
- gotcha While `fastapi-pagination` generally supports Pydantic V2, earlier versions of `fastapi-pagination` (pre-0.15.8) or specific Pydantic V2 minor versions (e.g., Pydantic <2.12.5) might encounter compatibility issues. FastAPI itself had a migration path from Pydantic V1 to V2, and users should ensure their FastAPI version is compatible with Pydantic V2.
Install
-
pip install "fastapi-pagination[full]" -
pip install fastapi-pagination -
pip install fastapi-pagination[sqlalchemy]
Imports
- Page
from fastapi_pagination import Page
- add_pagination
from fastapi_pagination import add_pagination
- paginate
from fastapi_pagination import paginate
- apaginate
from fastapi_pagination import apaginate
Quickstart
from fastapi import FastAPI
from pydantic import BaseModel, Field
from fastapi_pagination import Page, add_pagination, paginate
app = FastAPI()
add_pagination(app)
class UserOut(BaseModel):
name: str = Field(..., example="Steve")
surname: str = Field(..., example="Jobs")
# Simulate a database/data source
users_db = [
{"name": "John", "surname": "Doe"},
{"name": "Jane", "surname": "Smith"},
{"name": "Peter", "surname": "Jones"},
{"name": "Alice", "surname": "Brown"},
{"name": "Bob", "surname": "White"},
{"name": "Charlie", "surname": "Green"},
{"name": "Diana", "surname": "Black"},
{"name": "Eve", "surname": "Red"},
{"name": "Frank", "surname": "Blue"},
{"name": "Grace", "surname": "Yellow"},
]
@app.get("/users", response_model=Page[UserOut])
async def get_users():
# paginate function processes the data to return a Page object
return paginate(users_db)
# To run this example:
# 1. Save as main.py
# 2. Run: uvicorn main:app --reload
# 3. Access in browser: http://127.0.0.1:8000/users?page=1&size=5