FastAPI Pagination

0.15.12 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates basic page-based pagination for an in-memory list. Define your response model with `Page[YourModel]`, call `add_pagination(app)`, and use `paginate()` on your data. For database-backed pagination, use the `paginate` function from the relevant `ext` module (e.g., `fastapi_pagination.ext.sqlalchemy`).

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

view raw JSON →