Currently Available: Need a skilled Software Developer for your next project?
Categories
APIs

Implementing Limit and Offset Pagination in APIs

When you call an API such as API Ninjas, you use pagination so your client, the software making the request, can fetch a large collection in smaller batches. You can use the same pattern when you build your own endpoint. With limit-and-offset pagination, you pass limit to cap how many results the server returns in one response, and offset to tell the server how many matching results to skip first. For example, when a client sends limit=20&offset=40, the server skips the first 40 matches and returns up to 20 results after them.

Use this approach when clients need straightforward numbered pages or direct access to a known position in a collection. To keep results reliable, make your server sort records in a stable order, validate both parameters, and document the endpoint’s defaults and maximum page size. When you call API Ninjas, check the documentation for the specific endpoint you want because each endpoint sets its own pagination parameters and limits.

How limit and offset select a page

The server first applies the request’s filters, then sorts the matching records, skips the requested offset, and returns up to the requested limit. If your API also accepts a page number starting at 1, the server can calculate the offset as (page - 1) * limit. Page 3 with 20 results per page therefore starts at offset 40.

The server needs to sort records in a predictable order. If your database query sorts only by a field that contains duplicate values, the database can return tied rows in a different order from one request to the next. Add a unique field, such as id, to break ties so every record has a fixed position:

SELECT id, created_at, name
FROM items
WHERE status = :status
ORDER BY created_at DESC, id DESC
LIMIT :limit
OFFSET :offset;

Here, the database filters by status, sorts by created_at and id, skips the requested offset, and returns up to limit rows. PostgreSQL’s SELECT documentation warns that the database does not guarantee a predictable subset for LIMIT and OFFSET unless the ORDER BY clause establishes a unique order.

Check API Ninjas endpoint rules individually

API Ninjas endpoints do not all follow the same pagination rules. Each endpoint documents its own parameters, defaults, limits, and access requirements.

Endpoint Documented behavior
Quotes, /v2/quotes The endpoint returns deterministic results. You need premium access to use limit and offset; limit ranges from 1 to 100 and defaults to 1, while offset defaults to 0.
City, /v1/city You need premium access to use limit and offset. The limit ranges from 1 to 30 and defaults to 1.
Population, /v1/population The endpoint returns up to five matching records and documents offset for reaching more results. Its parameter list does not document a configurable limit.
IPO Calendar, /v1/ipocalendar The endpoint returns up to 50 records by default. It supports a limit up to 1,000 and an offset that defaults to 0.

These details come from the Quotes, City, Population, and IPO Calendar endpoint pages. Check the page for the endpoint you plan to call rather than assuming another endpoint’s settings apply.

For example, a client with premium access can request the second 20-item slice of deterministic quotes like this:

curl -G "https://api.api-ninjas.com/v2/quotes" \
  --data-urlencode "limit=20" \
  --data-urlencode "offset=20" \
  -H "X-Api-Key: YOUR_API_KEY"

The next batch starts at offset=40 as long as the client keeps the same filters and ordering. The Quotes documentation describes an array response, and it does not document a total count or a next-page link. Build your client around the documented response instead of expecting pagination metadata that the endpoint does not promise. Keep the API key on a server you control rather than exposing a private key in browser code.

Set a clear contract for your own API

Document whether offset starts at zero, what limit defaults to, and the maximum page size. Also state what your server does when a client sends a negative offset, a non-integer value, or a limit above the maximum. You can either cap an excessive limit at your maximum or reject the request with an error; pick one behavior and document it. Microsoft’s API design guidance recommends documenting useful defaults and setting an upper bound on page size.

Validate the inputs before your server queries the database. Require limit to be an integer within the endpoint’s allowed range, and require offset to be a nonnegative integer. Apply the default limit when the client omits it, and enforce the maximum if the client sends a larger value. When your server runs these checks, callers can diagnose invalid requests more easily, and you stop a missing or oversized limit from returning an unexpectedly large response.

Decide what response metadata to include based on what your clients need. Your server can return a plain array of items, or it can wrap the items with fields such as the applied limit, the offset, and a flag showing whether more results remain. Returning a total count helps a client display the full number of matching records, but your database has to do extra work to compute it, so include it only when your API promises it. If your server returns only the array of items, a client should treat a short page as the end of the collection only when the endpoint contract says that rule holds.

Account for deep pages and changing data

Limit-and-offset pagination works well for short collections and numbered-page interfaces, but you will run into two problems as clients move deeper into a dataset. First, the database still has to process rows it skips, so a large offset can make a request more expensive. Second, if someone inserts or deletes a record before the client’s current position, the remaining rows shift. A client fetching the next page can then see a duplicate record or miss one entirely, even when the server uses a stable sort order. PostgreSQL documents the cost of skipped rows, though the exact performance hit depends on your database and query.

When clients browse deep into a dataset or query collections that change often, consider switching to keyset pagination. With keyset pagination, the client sends a cursor, a value or token that marks the last record it saw, and the server resumes after that known sort value instead of counting and skipping rows. You avoid the cost of large skips, though you give up the ability to jump straight to an arbitrary page number. Microsoft’s guidance on continuation tokens describes token-based continuation for REST requests. For more on the trade-offs, see why offset pagination fails in production and how cursor, offset, and link-header pagination compare.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *