Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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/books is the resource, the books.
  • page=1 is the second page, because counting starts at zero.
  • size=5 means five books on each page.
  • sort=pages,desc orders 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.

All twelve books sorted by pages, longest first, then cut into pages of five. Page 0 is Emma 474 down to Dune and Good Omens 412. Page 1 is The Silmarillion 365, The Hobbit 310, Mort 272, Dune Messiah 256, Persuasion 249. Page 2 is Matilda 240 and The BFG 208. 1. sort all 12 by pages, desc 2. cut into pages of 5 Emma 474Children of Dune 444Pride and Prejudice 432Dune 412Good Omens 412 The Silmarillion 365The Hobbit 310Mort 272Dune Messiah 256Persuasion 249 Matilda 240The BFG 208 page 0offset 0, limit 5 page 1: what came backoffset 5, limit 5 page 2the last 2 books
Sort first, then cut into pages. Page 1 skips five rows and takes the next five.

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 limit and offset in 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=1000000 brings the original problem back.
  • Counting before filtering. totalElements must count the filtered rows, or the pager shows pages that are empty.

Quick recap

ParameterDefaultDoes
page0which page; becomes OFFSET page * size
size5 (1 to 100)books per page; becomes LIMIT size
sorttitlename or name,desc, checked against id, title, author, pages
authornonecase-insensitive "contains" filter
Responsecontent 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 12 of 26

Previous
POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
Next post
API Versioning in FastAPI with an API-Version Header

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.

On this page

  • Query parameters shape the answer
  • One request, one page back
  • A filter keeps only what matches
  • FastAPI reads the URL into parameters
  • Only sort by columns you allow
  • The database does the paging
  • The client builds its pager from four numbers
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.