How to Design Sort Parameter in API: Best Practices
Design the
sort parameter as a query string that accepts field names optionally prefixed with - for descending order, e.g., ?sort=field1,-field2. This approach allows clients to specify multiple sorting fields and directions in a simple, readable format.Syntax
The sort parameter is a query string used in API requests to specify sorting order. It typically accepts a comma-separated list of fields. Prefix a field with - to indicate descending order; otherwise, ascending order is assumed.
sort=field1: Sort byfield1ascending.sort=-field2: Sort byfield2descending.sort=field1,-field2: Sort byfield1ascending, thenfield2descending.
http
GET /items?sort=price,-rating
Example
This example shows a simple REST API endpoint that accepts a sort parameter and returns sorted items accordingly.
python
from flask import Flask, request, jsonify app = Flask(__name__) items = [ {"name": "Apple", "price": 5, "rating": 4.5}, {"name": "Banana", "price": 3, "rating": 4.7}, {"name": "Cherry", "price": 7, "rating": 4.2} ] @app.route('/items') def get_items(): sort_param = request.args.get('sort') sorted_items = items.copy() if sort_param: fields = sort_param.split(',') for field in reversed(fields): desc = field.startswith('-') key = field[1:] if desc else field sorted_items.sort(key=lambda x: x.get(key, None), reverse=desc) return jsonify(sorted_items) if __name__ == '__main__': app.run(debug=True)
Common Pitfalls
Common mistakes when designing or using the sort parameter include:
- Not supporting multiple fields, limiting sorting flexibility.
- Using unclear syntax, making it hard for clients to understand how to specify ascending or descending order.
- Failing to validate fields, which can cause errors or security issues.
- Ignoring case sensitivity or data types, leading to unexpected sort results.
Always document allowed fields and sorting rules clearly.
http
Wrong: GET /items?sort=price_desc Right: GET /items?sort=-price
Quick Reference
| Syntax | Meaning | Example |
|---|---|---|
| field | Sort by field ascending | sort=price |
| -field | Sort by field descending | sort=-rating |
| field1,field2 | Sort by multiple fields ascending | sort=name,price |
| field1,-field2 | Sort by first ascending, second descending | sort=name,-rating |
Key Takeaways
Use a comma-separated
sort query parameter with optional - prefix for descending order.Support multiple fields to allow flexible sorting by clients.
Clearly document allowed sort fields and syntax to avoid confusion.
Validate sort parameters to prevent errors and security issues.
Keep the syntax simple and consistent for easy client use.