Back to all terms
ClientAPIrequestresponse
APIintermediate

API Filtering & Sorting

Conventions for allowing API consumers to filter collection results by field values and control the sort order via query parameters.

Also known as: Query Parameters, API Search Parameters

Description

Filtering and sorting are essential features for any API that returns collections, allowing consumers to narrow results and control ordering without fetching entire datasets. Filtering is typically implemented via query parameters that map to database WHERE clauses: /orders?status=shipped&customer_id=abc. For more complex filters, APIs may adopt a structured syntax like LHS brackets (status[ne]=cancelled), a filter query language, or a JSON-based filter object.

Sorting is commonly expressed as a sort or order_by query parameter with field names and direction indicators: ?sort=created_at:desc,total:asc or ?sort=-created_at,+total (using +/- prefix convention). The API should define which fields are sortable, validate sort parameters against an allowlist, and ensure corresponding database indexes exist to avoid full table scans. Default sorting should be deterministic -- typically by primary key or a timestamp plus primary key.

Security considerations are important: filter parameters must be validated and sanitized to prevent SQL injection, and the API should not allow filtering on sensitive fields (e.g., password hashes, internal flags). Performance-wise, exposing arbitrary filtering can lead to expensive queries, so APIs should define supported filter fields and operators explicitly in their documentation and OpenAPI spec, rejecting unsupported combinations with a 400 response.

Prompt Snippet

Support filtering via typed query parameters with explicit operator suffixes: ?status=active&amount[gte]=100&amount[lte]=500. Validate all filter fields against an allowlist; return 400 for unsupported fields or operators. Implement sorting with ?sort=created_at:desc,id:asc syntax and enforce that every sortable field has a corresponding database index. Always append the primary key as a tiebreaker sort field for deterministic ordering. Document all filterable/sortable fields in the OpenAPI spec with enum constraints.

Tags

filteringsortingquery-parameterscollections