Offset and limit pagination (skip and limit) is simple but slows down on deep pages and can skip or repeat rows when data changes; cursor (keyset) pagination continues after the last seen key and stays fast and stable.
Always cap the page size, and return a next cursor or total count if the client needs it.
from typing import Annotated
from fastapi import Query
from sqlalchemy import select
@app.get("/items")
async def list_items(
limit: Annotated[int, Query(ge=1, le=100)] = 20,
cursor: int | None = None,
session: AsyncSession = Depends(get_session),
):
stmt = select(ItemRow).order_by(ItemRow.id).limit(limit)
if cursor is not None:
stmt = stmt.where(ItemRow.id > cursor)
rows = (await session.scalars(stmt)).all()
next_cursor = rows[-1].id if len(rows) == limit else None
return {"items": [ItemOut.model_validate(r) for r in rows], "next_cursor": next_cursor}