0
0
Rest-apiHow-ToBeginner ยท 4 min read

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 by field1 ascending.
  • sort=-field2: Sort by field2 descending.
  • sort=field1,-field2: Sort by field1 ascending, then field2 descending.
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

SyntaxMeaningExample
fieldSort by field ascendingsort=price
-fieldSort by field descendingsort=-rating
field1,field2Sort by multiple fields ascendingsort=name,price
field1,-field2Sort by first ascending, second descendingsort=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.