Skip to main content

fastapi-object-pagination

Typed, async page objects for FastAPI, with one page shape for a SQL database and for a graph database.

A FastAPI endpoint paginated with this library 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.

Why it exists

It was extracted from a production application that reads part of its data from PostgreSQL and part of it from a Neo4j knowledge graph, and exposes both through the same REST API. Existing FastAPI pagination libraries cover SQLAlchemy well and graph stores not at all, so each backend ended up with its own page format and the frontend had to special-case them. Pulling the page object out into a library forced a single contract on both sides.

Installation

Pick the backends you need, as extras:

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

or with pip:

pip install 'fastapi-object-pagination[sqlmodel]'

Importing a backend whose extra is missing raises ImportError with the command to install it, rather than a bare ModuleNotFoundError from deep inside the call stack.

Usage

SQLModel

from collections.abc import AsyncIterator
from typing import Annotated

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

app = FastAPI()
engine = create_async_engine("postgresql+asyncpg://localhost/heroes")


class Hero(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    team: str


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


@app.get("/heroes")
async def list_heroes(
    session: Annotated[AsyncSession, Depends(get_session)],
    page: int = 1,
    size: int = 10,
) -> Page[Hero]:
    return await paginate(
        model=Hero,
        async_session=session,
        current_page=page,
        items_by_page=size,
        filters={"team__icontains": "preventers"},
        ordering=["-name"],
    )

paginate is generic over the model, so the return type is inferred: paginate(model=Hero, ...) is a Page[Hero], and mypy checks the endpoint signature against it.

Neontology

from fastapi import FastAPI
from fastapi_object_pagination import Page
from fastapi_object_pagination.neontology import paginate
from neontology import BaseNode

app = FastAPI()


class Person(BaseNode):
    __primarylabel__: str = "Person"
    __primaryproperty__: str = "name"

    name: str
    city: str


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

paginate_related does the same across a relationship, so a page of nodes can be restricted to those connected to another label.

Both take an optional serializer, for when the page should carry an API model rather than the node that was queried. The page is then typed on what the serializer returns.

from pydantic import BaseModel


class PersonOut(BaseModel):
    label: str


@app.get("/people/labels")
async def list_labels(page: int = 1, size: int = 10) -> Page[PersonOut]:
    return await paginate(
        model=Person,
        current_page=page,
        items_by_page=size,
        serializer=lambda person: PersonOut(label=f"{person.name} ({person.city})"),
    )

The page

{
  "items": [{"name": "Black Lion", "team": "Preventers"}],
  "item_count": 42,
  "page_count": 5,
  "current_page": 2,
  "items_by_page": 10,
  "previous_page_url": "?current_page=1&items_by_page=10",
  "next_page_url": "?current_page=3&items_by_page=10"
}

Page is a generic Pydantic model, so FastAPI documents the real item type in the OpenAPI schema.

Filters

Both backends take the same filter dictionary, with Django-style lookups: exact, iexact, contains, icontains, startswith, istartswith, endswith, iendswith, gt, gte, lt, lte, in, isnull. A key without a lookup means exact.

SQLModel keys are field names ("name__icontains"). Neontology keys are (node_class, field_lookup) tuples, because a Cypher query can touch several labels at once.

On PostgreSQL the in lookup is compiled to = ANY(ARRAY[...]) instead of IN (...), which plans better on large lists; other dialects keep IN.

Compatibility

Python 3.10, 3.11, 3.12, 3.13
Pydantic 2.x
SQLModel >= 0.0.25, with an async engine (sqlmodel.ext.asyncio.session.AsyncSession)
Neontology >= 2.2.2

FastAPI itself is not a dependency: the library only returns Pydantic models, so any FastAPI version that works with Pydantic 2 will serialize them.

Licence

MIT. See LICENSE.

Metadata

Release files for fastapi-object-pagination 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-object-pagination 0.1.1
File Size Uploaded Provenance Actions
fastapi_object_pagination-0.1.1.tar.gz 8.9 kB Without provenance Details for fastapi_object_pagination-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-object-pagination 0.1.1
File Interpreter ABI Platform Actions
fastapi_object_pagination-0.1.1-py3-none-any.whl Python 3 none any Details for fastapi_object_pagination-0.1.1-py3-none-any.whl

Total release size: 22.1 kB

Release files / fastapi_object_pagination-0.1.1.tar.gz

Download URL fastapi_object_pagination-0.1.1.tar.gz
Size 8.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a643ed870c0090284365ddf102b72fc87e63db3c4fef10b6468f5ac0932c710a
BLAKE2b-256 checksum
How to use checksums
36eee11affcf9eac7aaeb98ce9c826c718d5b40a78ba2e81aaef1d77925a8281
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / fastapi_object_pagination-0.1.1-py3-none-any.whl

Download URL fastapi_object_pagination-0.1.1-py3-none-any.whl
Size 13.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
598ad1fe24af2eb25047b4eaedcd3ce934a529c21b2f634df07587a6b7ebbb45
BLAKE2b-256 checksum
How to use checksums
ddabae564d6f521bc4e95eac19a96dbf5b7b8be16f206ae3afaf59b3c7ac69c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for fastapi-object-pagination 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page