Find a course

Module 4: Using Real APIsLesson 8 of 1214 min

Query Parameters, Filtering and Pagination

Use query parameters to filter, sort and search API data, encode values safely, and page through large collections with offset and cursor pagination.

Step 1 of 14Learn

Asking for exactly what you need

An online store's API might hold two million products. GET /products can't return all of them at once: the response would be hundreds of megabytes and take minutes. Instead, clients narrow the request with query parameters:

GET /products?category=shoes&color=red&maxPrice=80&sort=-rating&limit=20

Common uses:

  • Filtering: category=shoes, status=open, createdAfter=2026-01-01.
  • Searching: q=running shoes for free-text search.
  • Sorting: sort=price for ascending; many APIs use a minus sign, sort=-price, for descending. Some use sort=price&order=desc instead.
  • Field selection: fields=id,name,price to receive only the fields you need.
  • Pagination: limit=20&offset=40 or page=3, covered below.

Query parameters belong to GET requests for reading collections. They are optional modifiers on a resource, not a different resource: /products?color=red is still the products collection, just filtered. By contrast, the path identifies which resource: /products/981 is one specific product.

A design rule worth following: parameters should combine predictably. color=red&size=42 should mean products that are red and size 42. When an API allows multiple values for one filter, it usually documents a format such as color=red,blue or color=red&color=blue.

Step 2 of 14Practice · Sort into groups

Should each piece of information go in the path or in the query string?

Tap an item, then tap its group (or drag it there).

Step 3 of 14Learn

Encoding values safely

URLs may contain only a limited set of characters. Spaces, &, =, ?, #, non-English letters and many symbols must be percent-encoded: replaced with % followed by two hexadecimal digits of the character's byte value.

  • A space becomes %20 (or + in query strings)
  • & becomes %26
  • é becomes %C3%A9 (its two UTF-8 bytes)

Why it matters: if a user searches for salt & pepper, the naive URL /search?q=salt & pepper breaks. The & starts a new parameter, so the server sees q=salt and a mysterious parameter named pepper. Correctly encoded, it's /search?q=salt%20%26%20pepper.

Never build query strings by gluing text together. Use the tools your language provides:

const params = new URLSearchParams({ q: 'salt & pepper', limit: 10 });
const url = 'https://api.example.com/search?' + params.toString();
// https://api.example.com/search?q=salt+%26+pepper&limit=10
import urllib.parse
urllib.parse.urlencode({"q": "salt & pepper", "limit": 10})
# 'q=salt+%26+pepper&limit=10'

The popular Python requests library goes one step further: pass params={"q": "salt & pepper"} and it encodes for you.

Encoding isn't only about correctness. Gluing raw user input into URLs can let attackers inject extra parameters, so proper encoding is also a basic security habit.

Step 4 of 14Practice · Code challenge

Write buildSearchUrl(base, params) that returns base + "?" + encoded query string for an object of parameters, using URLSearchParams so that special characters are encoded. If params has no keys, return base unchanged (no ?).

Runs in a sandbox in your browser.
  • buildSearchUrl("https://api.x.com/search", { q: "salt & pepper", limit: 10 })
  • buildSearchUrl("https://api.x.com/items", {})
  • buildSearchUrl("/books", { author: "Brontë", page: 2 })

Step 5 of 14Flashcards

Percent-encoding at a glance

Tap a card to flip it.

Step 6 of 14Learn

Pagination: offset and cursor

Collections are returned in pages. Two styles dominate.

Offset pagination uses limit (page size) and offset (how many items to skip), or the equivalent page and pageSize:

GET /products?limit=20&offset=0     items 1–20
GET /products?limit=20&offset=20    items 21–40
GET /products?limit=20&offset=40    items 41–60

It's simple and lets users jump to page 37 directly. Its weaknesses show on big or busy collections: if new items are inserted while you page, items shift and you may see duplicates or miss some; and for large offsets, databases must skip over many rows, which gets slow.

Cursor pagination returns an opaque cursor pointing at where the page ended, and you pass it to get the next page:

{
  "data": [ { "id": 981 }, { "id": 980 } ],
  "nextCursor": "eyJpZCI6OTgwfQ",
  "hasMore": true
}
GET /products?limit=20&cursor=eyJpZCI6OTgwfQ

Cursors stay correct when data changes and stay fast at any depth, which is why large social and payment APIs prefer them. The trade-off: you can only move forward (and sometimes back) one page at a time, not jump to page 37.

Either way, a good paginated response tells the client how to continue, with a next cursor, a next link, or a total count. Some APIs put the links in a Link header instead of the body.

Step 7 of 14Try the calculator

Offset pagination calculator

See how many requests it takes to download a whole collection, and which offset a given page starts at.

Requests needed for everything
13
Offset for that page
300
Items on the last page
50

Step 8 of 14Practice · Work it out

An API has 1,250 matching orders and a maximum page size of 100. Using offset pagination, what offset should the request for the 7th page use?

Step 9 of 14Practice · Work it out

Using the same collection (1,250 orders, 100 per page), how many requests does it take to download every order?

Step 10 of 14Compare

Offset vs cursor pagination

AspectOffset (limit + offset)Cursor (after=token)
Jump to page 40EasyNot possible directly
Items added while pagingCan shift results: duplicates or gapsStable: continues after the last item seen
Speed on deep pagesSlows down (database skips rows)Stays fast
Typical useAdmin tables with page numbersFeeds, logs, large exports

Step 11 of 14Note

Step 12 of 14Learn

Sorting, filtering and stable order

Pagination only works if the order of results is stable. Suppose an API sorts products by price and returns 20 per page. If 30 products cost exactly $19.99, the database may return those ties in a different order on each request, so a product can appear on both page 1 and page 2 while another never appears at all.

The fix is a tiebreaker: sort by the requested field, then by a unique field such as the ID. ORDER BY price, id gives exactly one possible order, so pages never overlap. Cursor-based APIs rely on this too: the cursor typically encodes both the last price and the last ID.

Filtering has its own pitfalls:

  • Document the semantics. Does createdAfter=2026-03-01 include March 1? Is it in UTC? Small ambiguities cause off-by-one-day bugs.
  • Validate inputs. limit=1000000 should be capped at a documented maximum, such as 100, or rejected with 400. Otherwise one request can overload the database.
  • Return what was applied. Echoing the effective filters and limit in the response helps clients notice when a value was capped or ignored.

As a client, read the docs for the default sort order and the maximum page size before writing a loop that downloads a collection.

Step 13 of 14Practice · True or false

If an API sorts by a non-unique field such as price without a tiebreaker, items with equal prices can appear on two pages or be skipped while paging.

Step 14 of 14Practice · Choose one

A social app shows a feed where new posts arrive every second. Users report seeing the same post twice when they scroll to the next page. Which change most directly fixes this?