Paging, Sorting and Filtering a REST API in FastAPI
Twelve books are fine in one answer; twelve thousand are not. Add page, size, sort and author query parameters to a FastAPI list endpoint, let SQLAlchemy page in the database, and return the four numbers a client needs for its pager.
What you will learn
- Shape a list response with page, size, sort and filter query parameters
- Read query parameters with defaults and limits using FastAPI's Query
- Let the database do the paging with ORDER BY, LIMIT, OFFSET and a COUNT query
- Return page metadata a client can build a pager from
Before you start
- A first FastAPI API with routes
- Pydantic request and response models
- Basic SQL: SELECT, WHERE, ORDER BY
Our library has twelve books, and sending all twelve in one answer is fine. Twelve thousand would not be: the answer gets slow, and nobody wants to scroll through twelve thousand books on a phone. So the client asks for one page at a time, and says which page, how many books and in what order, all in the URL.
Four small ideas: page, size, sort and a filter. This builds on the Book API from Pydantic request and response models.
Query parameters shape the answer
Here is the address we'll use:
GET /api/books?page=1&size=5&sort=pages,desc
/api/booksis the resource, the books.page=1is the second page, because counting starts at zero.size=5means five books on each page.sort=pages,descorders the books by their page count, biggest first.
The query parameters shape the answer; they don't change which resource you're asking for. That's why they go after the ? and not into the path (see RESTful API basics for resources and paths).
One request, one page back
The server answers 200 with five books and a page object at the bottom:
{"content":[{"id":9,"title":"The Silmarillion","author":"J.R.R. Tolkien","pages":365},{"id":1,"title":"The Hobbit","author":"J.R.R. Tolkien","pages":310},{"id":11,"title":"Mort","author":"Terry Pratchett","pages":272},{"id":5,"title":"Dune Messiah","author":"Frank Herbert","pages":256},{"id":4,"title":"Persuasion","author":"Jane Austen","pages":249}],"page":{"size":5,"number":1,"totalElements":12,"totalPages":3}}
Why those five? Because the server sorts first and then cuts the list into pages.
A filter keeps only what matches
GET /api/books?author=austen
{"content":[{"id":3,"title":"Emma","author":"Jane Austen","pages":474},{"id":4,"title":"Persuasion","author":"Jane Austen","pages":249},{"id":8,"title":"Pride and Prejudice","author":"Jane Austen","pages":432}],"page":{"size":5,"number":0,"totalElements":3,"totalPages":1}}
The filter keeps only the Jane Austen books and the rest drop out. No sort was given, so they come back by title, which is the default. totalElements is now 3, counted after filtering. Filters and sorting combine: ?author=austen&sort=pages returns the same three books ordered Persuasion (249), Pride and Prejudice (432), Emma (474).
FastAPI reads the URL into parameters
@router.get(
"",
response_model=PagedModelBookResponse,
summary="List books, a page at a time",
operation_id="list",
)
def list_books(
author: str | None = None,
page: int = Query(0, ge=0),
size: int = Query(5, ge=1, le=100),
sort: list[str] = Query(["title"]),
service: BookService = Depends(get_service),
):
books, total = service.list_page(author, page, size, sort)
return PagedModelBookResponse(
content=books,
page=PageMetadata(size=size, number=page, totalElements=total, totalPages=ceil(total / size)),
)
author defaults to None, so it's optional. page, size and sort are read with Query, and each has a default: page 0, five books per page, sorted by title. If the client sends nothing, those defaults are used. FastAPI matches the URL's parameters to the function's parameters by name.
Query also sets limits: ge=0 means a page can't be negative, and le=100 caps the page size so nobody can ask for a million rows at once. A value outside the limits never reaches your code; FastAPI rejects it as a validation error (in this project, turned into a 400 Problem Details answer). sort is a list[str], so a client may repeat it, as in ?sort=author&sort=pages,desc.
The response models are small:
class PageMetadata(BaseModel):
# camelCase on purpose: the same JSON the Java version of this API sends
size: int
number: int
totalElements: int
totalPages: int
class PagedModelBookResponse(BaseModel):
content: list[BookResponse]
page: PageMetadata
Only sort by columns you allow
A sort parameter turns into an ORDER BY, so it should never be passed straight through. The service checks each one against a fixed set:
SORTABLE = {"id", "title", "author", "pages"}
def list_page(self, author: str | None, page: int, size: int, sort: list[str]):
orders = []
for text in sort: # "pages,desc" -> ("pages", True)
name, _, direction = text.partition(",")
if name not in SORTABLE or direction.lower() not in ("", "asc", "desc"):
raise InvalidSort(text)
orders.append((name, direction.lower() == "desc"))
return self.repository.find_page(author, page, size, orders)
"pages,desc" becomes ("pages", True). Anything else, such as an unknown column or a direction other than asc or desc, raises InvalidSort, which the project answers as 400 with the title "Invalid sort" and the detail "Cannot sort by '...'". (That case isn't in the saved run, so there's no captured response to show here.)
The database does the paging
def find_page(self, author: str | None, page: int, size: int, orders: list[tuple[str, bool]]):
query = select(Book)
if author:
query = query.where(Book.author.ilike(f"%{author}%"))
total = self.db.scalar(select(func.count()).select_from(query.subquery()))
columns = [getattr(Book, name).desc() if desc else getattr(Book, name) for name, desc in orders]
rows = self.db.scalars(query.order_by(*columns, Book.id).offset(page * size).limit(size))
return list(rows), total
Two lines do the work. The where keeps only books whose author contains the text, ignoring case (ilike). The last query sorts, skips the books on earlier pages with offset(page * size), and takes size rows with limit. The extra Book.id at the end of order_by breaks ties, so books with the same page count (Dune and Good Omens both have 412) always land in the same order and never jump between pages.
SQLAlchemy sends two selects. Here they are from the run for ?page=1&size=5&sort=pages,desc:
SELECT count(*) AS count_1
FROM (SELECT book.id AS id, book.title AS title, book.author AS author, book.pages AS pages, book.shelf_code AS shelf_code
FROM book) AS anon_1
SELECT book.id, book.title, book.author, book.pages, book.shelf_code
FROM book ORDER BY book.pages DESC, book.id
LIMIT ? OFFSET ?
-- parameters: (5, 5)
The count gives totalElements. The second select fetches five rows, skipping five. And with ?author=austen, both queries gain WHERE lower(book.author) LIKE lower(?) with the parameter '%austen%'. The database does the paging, so only five rows travel to Python.
The client builds its pager from four numbers
"page":{"size":5,"number":1,"totalElements":12,"totalPages":3}
size is the books per page, number the page we're on, totalElements all the matching books, and totalPages is ceil(12 / 5) = 3. A phone app with Previous and Next buttons adds one to number and shows "Page 2 of 3", with both buttons active because we're in the middle. (The camelCase field names match the Java version of this API on purpose, so the same client works with both. The API contract for a React client shows a React app reading this exact page note.)
Common mistakes
- Paging in Python. Loading every row and slicing a list defeats the purpose. Use
limitandoffsetin the query. - No tie-breaker in the sort. Rows with equal values can swap between requests, so a book shows up on two pages or on none.
- Sorting by any column name the client sends. Check it against an allowed set.
- No upper limit on size.
size=1000000brings the original problem back. - Counting before filtering.
totalElementsmust count the filtered rows, or the pager shows pages that are empty.
Quick recap
| Parameter | Default | Does |
|---|---|---|
page | 0 | which page; becomes OFFSET page * size |
size | 5 (1 to 100) | books per page; becomes LIMIT size |
sort | title | name or name,desc, checked against id, title, author, pages |
author | none | case-insensitive "contains" filter |
| Response | content plus page: size, number, totalElements, totalPages |
Try it yourself
Run the project (uvicorn library.main:app --reload --port 8080) and send the requests in requests.http. Then ask for ?page=2&size=5&sort=pages,desc and predict the two books before you look, and try ?sort=shelf_code to see the sort check refuse it. As a next step, add a title filter next to author.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
