Skip to content

Sorting in REST APIs — Complete Guide

DodaTech Updated 2026-06-28 3 min read

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

  1. Not whitelisting sortable fields — Allowing sorting on any field can expose unnecessary database indexes or cause slow queries on unindexed fields.
  2. Inconsistent sort direction syntax — Using - for descending in some endpoints and desc in others confuses clients. Pick one pattern.
  3. Ignoring case sensitivity in string sorting — Database default collation may sort A-Z before a-z, or vice versa. Ensure consistent behavior.
  4. Returning unordered results by default — Always provide a default sort order. The default should be meaningful (typically by creation date descending) or by ID.
  5. 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

  1. What does the minus prefix mean in sort parameters?
  2. How do you sort by multiple fields?
  3. What is the default sort order if no sort parameter is provided?
  4. Why should you whitelist sortable fields?
  5. 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

What is the default sort order in REST APIs?

Most APIs default to sorting by ID ascending or creation date descending. Document your default so clients know what to expect.

How do I sort by related resource fields?

Use dot notation: ?sort=category.name or ?sort=-author.rating. The server joins the related table and sorts by the referenced field.

Is sorting case-sensitive?

By default, database string sorting is often case-sensitive. Make sorting case-insensitive by using LOWER() or a case-insensitive collation.

What happens if I sort by a non-existent field?

Return a 400 Bad Request with a message listing the allowed sortable fields. Never silently ignore invalid sort parameters.

Can I combine sorting with filtering?

Yes, sorting and filtering work together. The filter narrows the result set, and then the sort order is applied to the filtered results.

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