FastAPI Pagination
Add page-based and cursor pagination to FastAPI endpoints with a single paginate call.
Repository Health
Technical Analysis
fastapi-pagination is a Python library that makes pagination in FastAPI applications almost effortless. Instead of hand-rolling limit/offset parameters and response envelopes, you declare a Page return type and call a paginate function, and the library handles query parameters, slicing, and the paginated response schema for you.
It supports multiple pagination strategies, including page-number and cursor-based pagination, and integrates with a wide range of SQL and NoSQL backends such as SQLAlchemy, Tortoise ORM, and PyMongo. It is fully async-compatible and ships with typed models built on Pydantic.
What You Get
- A
paginatefunction andPage/LimitOffsetPageresponse models for instant pagination - Page-number, limit/offset, and cursor-based pagination strategies
- Integrations for SQLAlchemy, Tortoise ORM, PyMongo, and many other backends
- Full async/await support
- Pydantic-based typed responses and customizable page schemas
Common Use Cases
- Paginating list endpoints backed by a SQLAlchemy or Tortoise ORM query
- Adding cursor-based pagination to high-volume or infinite-scroll APIs
- Returning consistent, typed paginated response envelopes across an API
Under The Hood
Architecture - The library is organized around a small set of core abstractions in the fastapi_pagination package: bases.py defines the abstract page/params types, default.py and limit_offset.py provide the concrete Page and LimitOffsetPage models, and cursor.py implements cursor-based paging. api.py exposes the top-level paginate and add_pagination functions, using a request-scoped context (managed via FastAPI dependencies) to inject pagination parameters and slice results. A large ext/ package contains per-backend adapters (SQLAlchemy, Tortoise, PyMongo, and many more), and customization.py plus flow.py/flows.py support customizing page shape and paginate behavior.
Tech Stack - Pure Python (3.10+) built on FastAPI and Pydantic for the typed models and dependency injection, with optional extras pulling in the various supported ORM/database libraries only when their adapters are used.
Code Quality - The repository has an extensive, well-structured test suite (test_api, test_cursor, test_async_paginator, test_bases, plus base/ and ext/ subsuites and shared conftest/schemas fixtures) with codecov coverage tracking and CI. The code is fully typed with a py.typed marker, and the modular ext layout keeps backend-specific logic isolated and testable.
API Design - Developer experience is the standout: adding pagination is typically two lines — set the endpoint return type to Page[Model] and call paginate(data) — while add_pagination wires the query parameters app-wide. The consistent paginate interface across SQL and NoSQL backends, thorough documentation site, and sensible defaults give the library a very gentle learning curve.