0
0
Rest-apiHow-ToBeginner · 4 min read

How to Implement Sorting in REST API: Simple Guide

To implement sorting in a REST API, accept query parameters like sort to specify the field and order (e.g., sort=name or sort=-date). Use these parameters in your backend to order the data before sending the response.
📐

Syntax

Sorting in REST APIs is usually done by adding a sort query parameter to the request URL. The parameter value specifies the field to sort by and optionally the order.

  • sort=field: Sort by field in ascending order.
  • sort=-field: Sort by field in descending order (the minus sign means descending).

Example URL: /api/items?sort=price sorts items by price ascending, while /api/items?sort=-price sorts descending.

http
/api/items?sort=field
/api/items?sort=-field
💻

Example

This example shows a simple REST API endpoint in Node.js using Express that supports sorting items by a query parameter.

javascript
import express from 'express';
const app = express();

const items = [
  { id: 1, name: 'Apple', price: 100 },
  { id: 2, name: 'Banana', price: 50 },
  { id: 3, name: 'Cherry', price: 75 }
];

app.get('/api/items', (req, res) => {
  const sortParam = req.query.sort || 'id';
  const sortField = sortParam.startsWith('-') ? sortParam.slice(1) : sortParam;
  const sortOrder = sortParam.startsWith('-') ? -1 : 1;

  const sortedItems = [...items].sort((a, b) => {
    if (a[sortField] < b[sortField]) return -1 * sortOrder;
    if (a[sortField] > b[sortField]) return 1 * sortOrder;
    return 0;
  });

  res.json(sortedItems);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));
⚠️

Common Pitfalls

Common mistakes when implementing sorting in REST APIs include:

  • Not validating the sort parameter, which can cause errors or security issues.
  • Ignoring case sensitivity, leading to unexpected order.
  • Not supporting multiple sort fields when needed.
  • Returning unsorted data if the parameter is missing or invalid without clear behavior.

Always validate the field names and handle missing or invalid parameters gracefully.

javascript
/* Wrong: No validation, may crash or sort by undefined */
app.get('/api/items', (req, res) => {
  const sortParam = req.query.sort;
  const sortedItems = [...items].sort((a, b) => a[sortParam] - b[sortParam]);
  res.json(sortedItems);
});

/* Right: Validate and default to 'id' */
const allowedFields = ['id', 'name', 'price'];
app.get('/api/items', (req, res) => {
  let sortParam = req.query.sort || 'id';
  const desc = sortParam.startsWith('-');
  const field = desc ? sortParam.slice(1) : sortParam;
  if (!allowedFields.includes(field)) {
    sortParam = 'id';
  }
  const sortOrder = desc ? -1 : 1;
  const sortedItems = [...items].sort((a, b) => {
    if (a[field] < b[field]) return -1 * sortOrder;
    if (a[field] > b[field]) return 1 * sortOrder;
    return 0;
  });
  res.json(sortedItems);
});
📊

Quick Reference

Summary tips for sorting in REST APIs:

  • Use a sort query parameter with field names.
  • Prefix with - for descending order.
  • Validate allowed fields to avoid errors.
  • Support default sorting if no parameter is given.
  • Consider supporting multiple fields separated by commas for advanced sorting.

Key Takeaways

Use a query parameter like sort to specify sorting field and order in REST APIs.
Validate the sorting field to prevent errors and security issues.
Use a minus sign prefix to indicate descending order.
Provide a default sorting behavior when no parameter is given.
Consider supporting multiple sort fields for more flexible sorting.