0
0
FastAPIframework~5 mins

Pagination patterns in FastAPI

Choose your learning style9 modes available
Introduction

Pagination helps split large lists into smaller parts. This makes data easier to handle and faster to load.

Showing search results in small groups instead of all at once.
Displaying user comments page by page on a blog.
Loading product lists in an online store gradually.
Fetching database records in chunks to save memory.
Syntax
FastAPI
from fastapi import FastAPI, Query
from typing import List

app = FastAPI()

@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    items = [f"item{i}" for i in range(100)]
    return items[skip : skip + limit]

skip tells how many items to skip from the start.

limit controls how many items to return after skipping.

Examples
Returns 5 items starting from the position given by skip.
FastAPI
async def read_items(skip: int = 0, limit: int = 5):
    items = [f"item{i}" for i in range(20)]
    return items[skip : skip + limit]
Uses page number and page size to calculate which items to return.
FastAPI
async def read_items(page: int = 1, size: int = 10):
    items = [f"item{i}" for i in range(50)]
    start = (page - 1) * size
    end = start + size
    return items[start:end]
Sample Program

This FastAPI app returns items in pages. You can ask for a page number and size. It returns that slice of items plus info about total items.

FastAPI
from fastapi import FastAPI, Query
from typing import List

app = FastAPI()

items = [f"item{i}" for i in range(1, 101)]  # 100 items

@app.get("/items/")
async def get_items(page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=50)):
    start = (page - 1) * size
    end = start + size
    return {
        "page": page,
        "size": size,
        "total_items": len(items),
        "items": items[start:end]
    }
OutputSuccess
Important Notes

Use Query to add validation like minimum and maximum values.

Keep page size reasonable to avoid slow responses.

Always return total count if possible to help clients know how many pages exist.

Summary

Pagination splits data into smaller, manageable parts.

Use skip and limit or page and size to control data slices.

Validate inputs and return helpful info like total items.