How to implement pagination in FastAPI

How to implement pagination in FastAPI

Why you need pagination

When you have a database table with thousands of records, returning all of them in a single HTTP response is a recipe for disaster. It consumes excessive memory, slows down your network transfer, and can crash your frontend application. Pagination solves this by breaking the data into smaller, manageable chunks called pages.

To implement this in FastAPI, you typically use query parameters to control two values: the skip (how many items to bypass) and the limit (how many items to return).

Implementing pagination with FastAPI

Here is how you can implement a paginated endpoint step-by-step.

  1. Define your dependencies. Instead of repeating code in every endpoint, create a reusable dependency function that extracts skip and limit from the request URL.
  2. Set default values. It is best practice to set a default skip of 0 and a default limit of 100. This prevents massive data leaks if a user accidentally forgets to provide parameters.
  3. Apply logic to your database query. Use the skip and limit values to slice your database result set.
from fastapi import FastAPI, Depends
from typing import List

app = FastAPI()

# Mock database
items_db = [{"id": i, "name": f"Item {i}"} for i in range(1, 101)]

def common_parameters(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

@app.get("/items/")
def read_items(commons: dict = Depends(common_parameters)):
    skip = commons["skip"]
    limit = commons["limit"]
    
    # Slice the list based on parameters
    return items_db[skip : skip + limit]

# To run this, save as main.py and use: uvicorn main:app --reload
# Request: GET /items/?skip=0&limit=5
# Response: [{"id": 1, "name": "Item 1"}, ..., {"id": 5, "name": "Item 5"}]

A common mistake developers make is failing to validate the input parameters. If a user passes a negative integer for skip or limit, it can break your slicing logic or cause unexpected behavior. You should use Query from FastAPI to enforce constraints like ge=0 (greater than or equal to 0).

from fastapi import FastAPI, Query, Depends

app = FastAPI()

async def paginate(skip: int = Query(0, ge=0), limit: int = Query(10, ge=1, le=100)):
    return {"skip": skip, "limit": limit}

@app.get("/items/")
async def get_items(pagination: dict = Depends(paginate)):
    # Now pagination["skip"] is guaranteed to be >= 0
    # and pagination["limit"] is between 1 and 100
    return {"message": "Success", "params": pagination}

# Example request: GET /items/?skip=-1&limit=500
# Response: 422 Unprocessable Entity (Validation Error)

By using Query(..., ge=0), you offload the validation work to FastAPI. If the user provides invalid input, the API automatically returns a clear 422 error message, protecting your backend logic from bad data.

Posted in: API

Comments 0

No comments yet. Be the first to comment.