Sorting in REST APIs — Complete Guide
In this tutorial, you will learn about Sorting in REST APIs. We cover key concepts, practical examples, and best practices to help you master this topic.
Sorting in REST API ilink "Api Design" >}} allows clients to order results by one or more fields using query parameters, typically with a sort parameter supporting field names prefixed by minus for descending order.
flowchart LR A[Client] -->|GET /users?sort=-created_at| B[Server] B --> C["ORDER BY created_at DESC"] A -->|GET /users?sort=name,-created_at| D[Server] D --> E["ORDER BY name ASC, created_at DESC"] style A fill:#e1f5fe style B fill:#c8e6c9 style D fill:#fff9c4
The common pattern is ?sort=field_name for ascending and ?sort=-field_name for descending. Multiple fields use comma separation: ?sort=last_name,-created_at. This gives clients flexible control over result ordering.
Think of sorting like arranging a deck of cards. Ascending sort (no prefix) is like ordering from low to high. Descending sort (minus prefix) is like ordering from high to low. Multiple sort fields are like first sorting by suit, then by rank within each suit.
Example: Single Field Sorting
import requests
# Ascending sort by name
response = requests.get(
"https://api.example.com/users",
params={"sort": "name"}
)
users = response.json()
names = [u["name"] for u in users]
print(f"Ascending: {names}")
# Descending sort by name
response = requests.get(
"https://api.example.com/users",
params={"sort": "-name"}
)
users = response.json()
names = [u["name"] for u in users]
print(f"Descending: {names}")
Expected output:
Ascending: ['Alice', 'Bob', 'Charlie', 'Diana']
Descending: ['Diana', 'Charlie', 'Bob', 'Alice']
Example: Multi-Field Sorting
import requests
# Sort by role (ascending), then by name (descending)
response = requests.get(
"https://api.example.com/users",
params={"sort": "role,-name"}
)
for user in response.json():
print(f"{user['role']:10s} {user['name']}")
Expected output:
admin Diana
admin Charlie
editor Bob
viewer Alice
Example: Sorting with Directional Syntax
import requests
# Alternative using asc/desc syntax
response = requests.get(
"https://api.example.com/orders",
params={
"sort": "total:desc,created_at:asc"
}
)
print(f"URL: {response.url}")
for order in response.json()[:3]:
print(f"Order {order['id']}: ${order['total']}")
Expected output:
URL: https://api.example.com/orders?sort=total:desc,created_at:asc
Order 5: $500.00
Order 3: $250.00
Order 1: $100.00
Common Mistakes
- Not whitelisting sortable fields — Allowing sorting on any field can expose unnecessary database indexes or cause slow queries on unindexed fields.
- Inconsistent sort direction syntax — Using
-for descending in some endpoints anddescin others confuses clients. Pick one pattern. - Ignoring case sensitivity in string sorting — Database default collation may sort A-Z before a-z, or vice versa. Ensure consistent behavior.
- Returning unordered results by default — Always provide a default sort order. The default should be meaningful (typically by creation date descending) or by ID.
- Sorting on the client side — Sorting on the server is more efficient. Avoid returning unsorted large datasets that clients must sort in memory.
Practice Questions
- What does the minus prefix mean in sort parameters?
- How do you sort by multiple fields?
- What is the default sort order if no sort parameter is provided?
- Why should you whitelist sortable fields?
- Challenge: Design a sort syntax for an e-commerce API that supports sorting by price, rating, popularity, and newest. Include ascending, descending, and multi-field combinations.
FAQ
Mini Project
Create a Python function that validates sort parameters against a whitelist of allowed fields and converts them to SQL ORDER BY clauses. Support the minus-prefix syntax and multi-field comma-separated syntax.
What's Next
Now learn about pagination in REST API Design.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro