API Filtering, Sorting, Pagination, and Field Selection
Build collection endpoints that let clients narrow, order, page through, and shape results without slow queries or unstable response behavior.
Collection endpoints need predictable rules for filters, sorting, pagination, and field selection. This guide compares offset and cursor pagination, shows how to keep ordering stable and page sizes bounded, and explains how allowlists and tenant checks limit query cost and data exposure. It also covers reused cursors, expensive counts, and unindexed filters, with practical controls for keeping collection APIs safe to operate.
API Filtering, Sorting, Pagination, and Field Selection
Introduction
Collection endpoints often need more than a single fixed response: clients may need to filter records, choose a stable order, move through pages, or request only a few fields. Each option changes the API contract and the database work required to serve it.
This guide follows one customer’s order collection through filters, ordering, cursor pagination, and field selection. It also explains how to keep the query bounded and permission-aware. For collection route and relationship design, see API Resource Names, Relationships, and Collections; for compatibility checks, see Executable API Contracts and Compatibility Testing.
Pagination choices
Offset pagination is easy to understand: limit=25&offset=50. It works well for small datasets, but deep offsets can require scanning many rows, and insertions between page requests can shift results. Cursor pagination instead continues after a stable position. The token should be opaque to clients; the server can store or protect the last sort values, including the unique tie-breaker. Cursors are not automatically snapshots; if a client needs a consistent export while data changes, use a snapshot or export job.
One order collection, one paged query
Assume the caller is authorized to read customer cus_42. These four records are in that customer’s collection:
| id | createdAt | status | totalMinor |
|---|---|---|---|
| ord_108 | 2026-10-12T10:15:00Z | shipped | 6499 |
| ord_107 | 2026-10-12T10:15:00Z | shipped | 12998 |
| ord_106 | 2026-10-12T10:10:00Z | shipped | 7999 |
| ord_105 | 2026-10-12T10:09:00Z | pending | 3300 |
The request filters to shipped orders, sorts by newest first, asks for two items, and selects four response fields. This API defines id DESC as the tie-breaker for equal timestamps, so its effective order is createdAt DESC, id DESC:
GET /v1/customers/cus_42/orders?status=shipped&sort=-createdAt&limit=2&fields=id%2CcreatedAt%2Cstatus%2CtotalMinor HTTP/1.1
Accept: application/json
The first page returns both orders at 10:15 in descending ID order. The cursor is opaque to the caller; internally it represents the last returned position, (2026-10-12T10:15:00Z, ord_107):
HTTP/1.1 200 OK
Content-Type: application/json
{
"items": [
{ "id": "ord_108", "createdAt": "2026-10-12T10:15:00Z", "status": "shipped", "totalMinor": 6499 },
{ "id": "ord_107", "createdAt": "2026-10-12T10:15:00Z", "status": "shipped", "totalMinor": 12998 }
],
"nextCursor": "cur_A7m2Qx9N"
}
The next request keeps the filter, sort, and field selection unchanged, adding only the returned cursor. This example also keeps limit=2; AIP-158 allows a client to change page size while keeping other arguments fixed.
GET /v1/customers/cus_42/orders?status=shipped&sort=-createdAt&limit=2&fields=id%2CcreatedAt%2Cstatus%2CtotalMinor&cursor=cur_A7m2Qx9N HTTP/1.1
Accept: application/json
The server rechecks that the caller can read this customer, applies the same filter, and continues strictly after the cursor’s timestamp-and-ID pair. The remaining shipped order is returned; by this API’s contract, omitting nextCursor means the collection has ended:
HTTP/1.1 200 OK
Content-Type: application/json
{
"items": [
{ "id": "ord_106", "createdAt": "2026-10-12T10:10:00Z", "status": "shipped", "totalMinor": 7999 }
]
}
In SQL-like terms, a descending keyset query uses the last row as an exclusive boundary:
WHERE tenant_id = :authorized_tenant
AND customer_id = :customer_id
AND status = :status
AND (
created_at < :cursor_created_at
OR (created_at = :cursor_created_at AND id < :cursor_id)
)
ORDER BY created_at DESC, id DESC
LIMIT :effective_limit_plus_one
Omit the cursor predicate on the first page. Fetching one extra row lets the service determine whether another page exists; build nextCursor from the last row returned to the client, not the extra row. Database syntax and index choices vary, but the ordering and comparison must agree. Cursors are navigation hints, not authorization grants or snapshots. Google’s AIP-158 pagination guidance requires opaque URL-safe tokens, keeps non-page-size arguments the same between pages, and allows the page size to change.
The comma separators in fields are percent-encoded in these requests. Build query strings with a URL library so reserved characters are encoded once; RFC 3986 explains percent-encoding and why URI components must be parsed before data is decoded.
Authorization scope
Authorization scope must be applied before filters and pagination. Otherwise results or page boundaries can expose records the caller cannot access. Check the same scope again on the next-page request; the cursor does not preserve earlier permission.
When to use and when not to use
Offset pagination is reasonable for small, relatively stable lists where numbered pages matter. For a large or changing collection, an indexed cursor order avoids scanning past an ever-growing offset, but does not give a consistent snapshot. Offer field selection only when clients need it and the server can allowlist the selectable fields.
Trade-off Analysis
| Feature | Strength | Cost |
|---|---|---|
| Offset pagination | Simple page numbers and links | Deep scans and shifting pages |
| Cursor pagination | Efficient continuation on indexed order | Less natural page jumps; cursor lifecycle |
| Field selection | Smaller payloads | More response variants and validation |
| Flexible filters | Serves varied clients | Query planning, indexing, and abuse risk |
Implementation snippet
Parse every client-controlled field through an allowlist. This example API defaults to 25 items and caps a page at 100; those values are service policy, not universal limits.
interface ListQuery {
status: string;
limit: number;
orderBy: readonly [string, string];
fields: string[];
cursor: string | null;
}
const SORTS = {
"-createdAt": ["created_at DESC", "id DESC"],
} as const;
const FIELDS: Record<string, string> = {
id: "id",
createdAt: "created_at",
status: "status",
totalMinor: "total_minor",
};
const STATUSES = new Set(["pending", "shipped"]);
function parseListQuery(url: URL): ListQuery {
const rawLimit = url.searchParams.get("limit");
if (rawLimit === "") throw new HttpError(400, "invalid_limit");
const requestedLimit = Number(rawLimit ?? 25);
if (!Number.isSafeInteger(requestedLimit) || requestedLimit < 0) {
throw new HttpError(400, "invalid_limit");
}
const limit = Math.min(requestedLimit === 0 ? 25 : requestedLimit, 100);
const sort = url.searchParams.get("sort") ?? "-createdAt";
if (!Object.hasOwn(SORTS, sort)) throw new HttpError(400, "invalid_sort");
const status = url.searchParams.get("status");
if (status === null || !STATUSES.has(status))
throw new HttpError(400, "invalid_filter");
const fields = (
url.searchParams.get("fields") ?? "id,createdAt,status,totalMinor"
).split(",");
if (
fields.length === 0 ||
fields.some((field) => !Object.hasOwn(FIELDS, field))
) {
throw new HttpError(400, "invalid_field");
}
return {
status,
limit,
orderBy: SORTS[sort as keyof typeof SORTS],
fields: fields.map((field) => FIELDS[field]),
cursor: url.searchParams.get("cursor"),
};
}
Use the mapped column names for SQL structure and bind customer, status, and cursor values as parameters. Never interpolate a raw field name, direction, or filter value. Verify a cursor’s signature or lookup record, check its filter/order/field-selection context, then reapply authorization. The example keeps the supported sort narrow; add sort modes only with matching cursor predicates and index support.
| Invalid query | Contract response | Why |
|---|---|---|
sort=-internalNote |
400 invalid_sort |
Only documented sort keys are accepted |
fields=id,privateToken |
400 invalid_field |
Unknown or disallowed fields are rejected without exposing private schema details |
limit=two or limit=2.5 |
400 invalid_limit |
The value must be an integer |
limit=-1 |
400 invalid_limit |
Negative values are rejected |
limit=0 or omitted |
Effective limit is 25 |
This API uses its documented default |
limit=101 |
Effective limit is capped at 100 |
This API clamps values above its documented maximum |
Cursor reused with status=pending |
400 invalid_cursor |
Restart pagination when a cursor-bound filter or order changes |
Google AIP-158 recommends a documented default for an omitted or zero page size, rejecting negative values, and coercing a value above the maximum down to that maximum. Follow a consistent policy and document the actual limits for your service.
Production failure scenarios and mitigations
A client requests limit=1000000, exhausting memory; clamp limits and reject unreasonable values. A sort parameter interpolates raw SQL and enables injection; map known names to trusted columns. Offset pagination skips or repeats rows during frequent inserts; use cursor pagination over a deterministic order. A cursor is reused after permissions change; reapply authorization on every page and treat cursors as navigation hints, not access grants. An unindexed filter drives database CPU high; monitor query plans and restrict supported combinations.
Observability checklist
- Track requested and effective page sizes, response bytes, and query latency.
- Measure slow query rates by normalized filter and sort shape, not raw sensitive values.
- Watch invalid query rates and cursor expiration or decode failures.
- Alert on high-cardinality filter patterns that correlate with database saturation.
Security notes and pitfalls
Treat all query values as untrusted. Allowlist fields and operators, parameterize values, enforce per-tenant scope, and never expose fields that authorization forbids. Opaque cursors may be signed to detect tampering, but still reauthorize each request. Common mistakes include unstable sorting, unlimited page size, leaking total counts, interpreting empty filters inconsistently, and assuming a cursor itself grants permission.
Quick Recap Checklist
- Allowlist filter and sort fields, and validate requested values.
- Use a deterministic sort order with a unique tie-breaker for cursor pagination.
- Set a server-side maximum page size and define behavior for invalid limits.
- Return only authorized fields and avoid exposing sensitive data through field selection.
- Apply tenant permissions before pagination and measure query costs in production.
Interview Questions
The server needs a stable position from which to continue. A unique tie-breaker prevents records with equal primary sort values from moving unpredictably between pages.
It works for small, relatively stable result sets where page-number navigation matters and offsets remain shallow. For large or frequently changing collections, cursor pagination is usually more robust.
A server-side cap protects memory, response bandwidth, and database capacity. The API can return the effective page size or reject invalid values according to its documented contract.
Scope the query to records the caller may access before calculating pages or counts. Filtering unauthorized records afterward can expose their presence through result sizes, page gaps, or continuation tokens.
A cursor identifies where to continue in an ordering, but later pages may still reflect live data changes. A snapshot fixes the dataset for the duration of an export or traversal and may require separate server-side state.
Counting can require an expensive query, especially with complex filters or large datasets. Counts can also reveal information about records a caller should not infer, so return them only when the cost and access rules are clear.
Allowlist selectable fields and enforce authorization for each one. Field selection can reduce payloads, but it creates more response variants to validate, document, cache, and test.
Choose a consistent policy and document it. Rejecting unknown names catches typos early; ignoring them can support forward compatibility, but may silently return broader results than the caller intended.
Permissions can change after the first page, and a cursor is only a navigation hint. Rechecking access on each request prevents an old token from bypassing current tenant or resource permissions.
Further Reading
- API Resource Names, Relationships, and Collections — Collection design, route structure, and relationship choices.
- Executable API Contracts and Compatibility Testing — Keep request parameters and response shapes compatible.
- Google API Improvement Proposal 132: List — Conventions for listing collections.
- Google API Improvement Proposal 158: Pagination — Page tokens, bounded page sizes, and continuation behavior.
- Google API Improvement Proposal 157: Partial Responses — View enums and field-mask parameters for selecting response fields.
Conclusion
Collection query options are part of the API contract and part of the server’s resource budget. Keep them bounded, predictable, permission-aware, and backed by measured query plans.
Category
Related Posts
API Request, Response, and Error Shapes Clients Can Trust
Design consistent API request and response envelopes, validation errors, and problem details so client developers can handle success and failure reliably.
API Resource Names, Relationships, and Collections
Model API URLs around stable resources and relationships, with clear collection behavior that clients can navigate without learning server internals.
HTTP Methods, Status Codes, and Headers in API Design
Choose HTTP methods that match the operation, return status codes clients can act on, and use headers for metadata, caching, and safe retries.