Skip to content

fastapi-object-pagination

fastapi-object-pagination

fastapi-object-pagination, typed async pages for FastAPI, from a SQL or a graph database.

License: MIT Status: beta Python 3.11+


Documentation: https://fastapi-object-pagination.businessagile.eu

Source Code: https://github.com/BiBzz/fastapi-object-pagination

Created by: Alexandre BERREBI, maintained by Business Agile


fastapi-object-pagination paginates a FastAPI endpoint and returns a Page[Model]: the items, the counts, and the URLs of the previous and next pages. The same Page comes back whether the data was read through SQLModel or through Neontology (Neo4j and Memgraph), so the clients of the API, and its OpenAPI schema, do not change when the storage does.

The key features are:

  • One page shape: Page is a generic Pydantic model. A page of SQL rows and a page of graph nodes have the same fields and the same JSON.
  • Typed: paginate(model=Book, ...) returns a Page[Book], so mypy checks the endpoint signature, and FastAPI documents the real item type in the OpenAPI schema.
  • Async: the SQLModel backend runs on an AsyncSession, and every entry point is a coroutine you await in an async def endpoint.
  • Django style filters: {"author__iexact": "jane austen"} for SQLModel, {(Company, "name__iexact"): "acme"} for Neontology, with the same fourteen lookups on both sides.
  • Ordering: ["-year", "title"], a minus sign for descending.
  • Across relationships: paginate_related pages the nodes connected to another label, and filters on that label.
  • Serializers: a Neontology page can carry an API model built from each node instead of the node itself, and is typed on it.
  • Light: Pydantic is the only required dependency. Each backend is an extra, and importing one whose extra is missing tells you the command that installs it.

Requirements

A recent and currently supported version of Python: 3.11 or later.

Pydantic 2, installed with the library. FastAPI itself is not a dependency: the library returns Pydantic models, which any FastAPI version working with Pydantic 2 serializes.

And one of the backends:

  • SQLModel 0.0.25 or later, with an async engine (sqlmodel.ext.asyncio.session.AsyncSession).
  • Neontology 2.2.2 or later, connected to Neo4j or Memgraph.

Installation

Pick the backends you need, as extras:

$ pip install 'fastapi-object-pagination[sqlmodel]'
---> 100%

or with uv:

$ uv add 'fastapi-object-pagination[sqlmodel]'
$ uv add 'fastapi-object-pagination[neontology]'
$ uv add 'fastapi-object-pagination[sqlmodel,neontology]'

Example

A paginated endpoint

A table of books, read through SQLModel, and an endpoint that returns them a page at a time, filtered by author and ordered from the most recent:

from collections.abc import AsyncIterator
from typing import Annotated

from fastapi import Depends, FastAPI, Query
from sqlalchemy.ext.asyncio import create_async_engine
from sqlmodel import Field, SQLModel
from sqlmodel.ext.asyncio.session import AsyncSession

from fastapi_object_pagination import Page
from fastapi_object_pagination.sqlmodel import paginate


class Book(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    title: str
    author: str
    year: int


engine = create_async_engine("sqlite+aiosqlite:///books.db")
app = FastAPI()


async def get_session() -> AsyncIterator[AsyncSession]:
    async with AsyncSession(engine) as session:
        yield session


@app.get("/books")
async def list_books(
    session: Annotated[AsyncSession, Depends(get_session)],
    current_page: Annotated[int, Query(ge=1)] = 1,
    items_by_page: Annotated[int, Query(ge=1, le=100)] = 10,
    author: str | None = None,
) -> Page[Book]:
    return await paginate(
        model=Book,
        async_session=session,
        current_page=current_page,
        items_by_page=items_by_page,
        filters={"author__iexact": author} if author else None,
        ordering=["-year", "title"],
    )

paginate is generic over the model: paginate(model=Book, ...) is a Page[Book], and mypy checks it against the signature of the endpoint.

The query parameters are named current_page and items_by_page, like the ones the library writes in the URLs of the previous and next pages, so a client can follow them as they are.

The page

With six books by Jane Austen in the table, GET /books?author=jane austen&current_page=2&items_by_page=2 returns:

{
  "items": [
    {"author": "Jane Austen", "title": "Emma", "id": 4, "year": 1815},
    {"author": "Jane Austen", "title": "Mansfield Park", "id": 3, "year": 1814}
  ],
  "item_count": 6,
  "page_count": 3,
  "current_page": 2,
  "items_by_page": 2,
  "previous_page_url": "?current_page=1&items_by_page=2",
  "next_page_url": "?current_page=3&items_by_page=2"
}

The filter narrows the count as well as the items: item_count is six, not the size of the table.

The same page from a graph

With Neontology, the endpoint changes its import, not its response:

from fastapi import FastAPI

from fastapi_object_pagination import Page
from fastapi_object_pagination.neontology import paginate

from .models import Person

app = FastAPI()


@app.get("/people")
async def list_people(current_page: int = 1, items_by_page: int = 10) -> Page[Person]:
    return await paginate(
        model=Person,
        current_page=current_page,
        items_by_page=items_by_page,
    )

Person is a Neontology node, defined on the Neontology page, and the response has the same seven fields as the page of books.

Interactive documentation

FastAPI documents Page[Book] as its own schema, named Page_Book_, whose items are Book objects, so the generated clients and the /docs page show the real item type.

License

This project is licensed under the terms of the MIT license.