How to design API filtering and sorting
· Category: API & REST
Short answer
Filtering and sorting query parameters let clients retrieve precisely the data they need, reducing payload size and improving usability.
Steps
- Define filter operators such as eq, neq, gt, lt, contains, and in.
- Accept sort as a comma-separated list with optional direction prefixes like asc and desc.
- Support field selection via a fields or include parameter to limit response size.
- Validate and sanitize all query inputs to prevent injection attacks.
- Document supported filters, sortable columns, and default ordering.
Tips
- Use consistent naming conventions for query parameter keys.
- Escape special characters in filter values to avoid parsing ambiguities.
- Limit the complexity of nested filters to maintain query performance.
- Return 400 for unsupported filter fields rather than ignoring them silently.
Common issues
- SQL injection through unsanitized filter parameters.
- Sorting on unindexed columns causing full table scans.
- Inconsistent handling of null values in range filters.
- Overly complex query strings exceeding URL length limits.
Example
curl -X GET https://api.example.com/users -H "Accept: application/json" -H "Authorization: Bearer $TOKEN"
This curl command demonstrates a standard GET request with headers for content negotiation and bearer token authentication.