Backend Boilerplates python Intermediate

FastAPI Pagination Helper

Generic offset/limit pagination helper compatible with any SQLAlchemy query.

python
from fastapi import Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import func

async def paginate(query, session: AsyncSession, page: int = Query(1, ge=1), size: int = Query(20, le=100)):
    total = await session.scalar(query.with_only_columns(func.count()))
    items = (await session.execute(query.offset((page-1)*size).limit(size))).scalars().all()
    return {'items': items, 'total': total, 'page': page, 'pages': -(-total // size)}

Prerequisites

  • fastapi
  • sqlalchemy >= 2.0

Pro Tips

  • → Use cursor-based pagination for large datasets.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
python
Level
Intermediate
Read time
4 min
Published
Aug 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.