Lesson 79 of 158 – API Sorting
79%

API Sorting

API sorting allows a mobile application to control the order in which records are returned by the REST API. For example, students can be sorted by name, newest records can be shown first, or products can be sorted by price.

Note: Filtering decides which records are returned, while sorting decides the order of those records.

1. What is API Sorting?

API sorting means arranging API results according to a selected column or property.

Mobile App
    ↓
Sort Parameter
    ↓
REST API
    ↓
Database
    ↓
Sorted Records
    ↓
JSON Response

2. Why Do We Need Sorting?

Suppose a student application contains 500 students. Users may want to see students alphabetically by name or newest students first.

Instead of sorting everything on the mobile device, the API can request the database to return records in the required order.

3. Sorting Using Query Parameters

A common sorting URL is:

GET /api/students.php?sort=name

The API receives name as the requested sorting column.

4. Sorting Direction

Sorting normally has two directions:

Direction Meaning
ASC Ascending order
DESC Descending order
?sort=name&order=asc
?sort=name&order=desc

5. SQL ORDER BY

MySQL uses ORDER BY to sort query results.

SELECT *
FROM students
ORDER BY name ASC;

This returns students in ascending alphabetical order by name.

6. Descending Order

To display larger, newer, or later values first, use DESC.

SELECT *
FROM students
ORDER BY id DESC;

This can be useful for displaying recently inserted records first.

7. Sort Students by Name

SELECT
    id,
    student_id,
    name,
    course
FROM students
ORDER BY name ASC;

The result is arranged alphabetically by student name.

8. Sort Students by ID

SELECT *
FROM students
ORDER BY id DESC;

Using descending ID order commonly displays recently created records first when IDs increase as records are created.

9. Sort by Fee

Sorting is not limited to text fields.

SELECT *
FROM students
ORDER BY fee ASC;

This displays records from the lowest fee to the highest fee.

10. Sort by Date

Date columns can also be sorted.

SELECT *
FROM students
ORDER BY admission_date DESC;

This can show recently admitted students first.

11. Read Sort Parameter in PHP

$sort = $_GET['sort'] ?? 'id';

$order = $_GET['order'] ?? 'desc';

Default values can be used when the client does not send sorting parameters.

12. Validate Sort Direction

The sort direction should be restricted to known values.

$order = strtolower(
    $_GET['order'] ?? 'desc'
);

if (!in_array(
    $order,
    ['asc', 'desc'],
    true
)) {

    $order = 'desc';
}

This prevents unexpected values from being used as SQL syntax.

13. Validate Sort Column

Column names should not be accepted directly from the user. Create an allowlist of columns that the API permits.

$allowedSortColumns = [
    'id' => 'id',
    'name' => 'name',
    'fee' => 'fee',
    'admission_date' => 'admission_date'
];

$sort = $_GET['sort'] ?? 'id';

if (!isset($allowedSortColumns[$sort])) {

    $sort = 'id';
}

$sortColumn =
    $allowedSortColumns[$sort];

14. Why Validate Sort Columns?

A prepared statement placeholder is designed for values. It should not be treated as a direct placeholder for a SQL column name.

Therefore, dynamic sort columns should be selected from a trusted allowlist.

$allowedSortColumns = [
    'name' => 'name',
    'fee' => 'fee',
    'id' => 'id'
];

Only columns defined in the allowlist should be used in the ORDER BY clause.

15. Complete PHP Sorting API

<?php

header(
    "Content-Type: application/json"
);

require_once '../db.php';

$allowedSortColumns = [
    'id' => 'id',
    'name' => 'name',
    'fee' => 'fee',
    'admission_date' => 'admission_date'
];

$sort =
    $_GET['sort'] ?? 'id';

$order = strtolower(
    $_GET['order'] ?? 'desc'
);

if (!isset(
    $allowedSortColumns[$sort]
)) {

    $sort = 'id';
}

if (!in_array(
    $order,
    ['asc', 'desc'],
    true
)) {

    $order = 'desc';
}

$sortColumn =
    $allowedSortColumns[$sort];

try {

    $sql = "
        SELECT
            id,
            student_id,
            name,
            course,
            fee,
            admission_date
        FROM students
        ORDER BY $sortColumn $order
    ";

    $stmt = $pdo->prepare($sql);

    $stmt->execute();

    $students =
        $stmt->fetchAll(
            PDO::FETCH_ASSOC
        );

    echo json_encode([
        "success" => true,
        "sort" => $sort,
        "order" => $order,
        "data" => $students
    ]);

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" =>
            "Server error"
    ]);
}

?>

16. Sort by Name in API

To sort students by name in ascending order:

GET /api/students.php?sort=name&order=asc

Example result:

Amit
Anil
Rahul
Ravi
Vijay

17. Sort by Name Descending

GET /api/students.php?sort=name&order=desc

The results will be returned in reverse alphabetical order.

Vijay
Ravi
Rahul
Anil
Amit

18. Sort with Filtering

Sorting can be combined with filtering.

GET /api/students.php?status=active&sort=name&order=asc

The API first selects active students and then sorts the matching records by name.

SELECT *
FROM students
WHERE status = ?
ORDER BY name ASC;

19. Sort with Search

Search and sorting can also be combined.

GET /api/students.php?search=rahul&sort=name&order=asc

The API can search for matching students and then arrange the results.

20. React Native Fetch Sorting

const response = await fetch(
    "https://example.com/api/students.php"
    + "?sort=name"
    + "&order=asc"
);

const result =
    await response.json();

setStudents(
    result.data || []
);

The mobile application can request the required sorting order from the API.

21. Sorting with Axios

import axios from "axios";

const response = await axios.get(
    "https://example.com/api/students.php",
    {
        params: {
            sort: "name",
            order: "asc"
        }
    }
);

setStudents(
    response.data.data || []
);

22. Sort Selection in React Native

A mobile application can provide buttons or a dropdown for selecting the sort column.

const [sort, setSort] =
    useState("name");

const [order, setOrder] =
    useState("asc");

These values can be sent to the API.

23. Ascending and Descending Buttons

<Button
    title="A-Z"
    onPress={() => {
        setSort("name");
        setOrder("asc");
    }}
/>

<Button
    title="Z-A"
    onPress={() => {
        setSort("name");
        setOrder("desc");
    }}
/>

This provides a simple way for users to change the result order.

24. Sorting and FlatList

After receiving sorted data from the API, the React Native application can display it directly in a FlatList.

<FlatList
    data={students}
    keyExtractor={(item) =>
        item.id.toString()
    }
    renderItem={({ item }) => (
        <Text>
            {item.name}
        </Text>
    )}
/>

The order of the FlatList items follows the order returned by the API.

25. Sorting by Latest Records

Many applications need the newest records first.

GET /api/students.php?sort=id&order=desc

If IDs increase as records are created, this can commonly show newer records first.

For more accurate date-based ordering, use a dedicated timestamp or date column.

26. Sorting and SQL Injection

Dynamic sort columns require special care because a column name is part of the SQL statement.

Unsafe:

$sort = $_GET['sort'];

$sql =
    "SELECT *
     FROM students
     ORDER BY $sort";

Safer:

$allowedSortColumns = [
    'id' => 'id',
    'name' => 'name',
    'fee' => 'fee'
];

$sort =
    $_GET['sort'] ?? 'id';

if (!isset(
    $allowedSortColumns[$sort]
)) {

    $sort = 'id';
}

$sortColumn =
    $allowedSortColumns[$sort];

Always use an allowlist for dynamic SQL identifiers.

27. Sorting with Pagination

Sorting becomes especially important when an API uses pagination. The API should apply a consistent ordering before applying LIMIT and OFFSET.

SELECT *
FROM students
ORDER BY name ASC
LIMIT 20 OFFSET 0;

This helps keep pages predictable.

28. Test Sorting API in Postman

Method: GET

http://localhost/api/students.php?sort=name&order=asc

Click Send and check the order of the returned records.

You can also test:

http://localhost/api/students.php?sort=id&order=desc

Compare the results to understand ascending and descending order.

29. Complete Sorting Flow

React Native
     ↓
Select Sort Column
     ↓
Select ASC / DESC
     ↓
Query Parameters
     ↓
GET Request
     ↓
PHP REST API
     ↓
Validate Sort Column
     ↓
Validate Sort Direction
     ↓
ORDER BY
     ↓
MySQL
     ↓
Sorted JSON Data
     ↓
React Native FlatList

30. API Sorting Summary

API sorting allows the client to control the order of records returned by a REST API. PHP can read the requested sort field and direction, validate them using an allowlist, and build a safe ORDER BY clause.

GET /api/students.php?sort=name&order=asc

Sorting is especially useful when building student lists, product lists, payment reports, attendance records, and other mobile applications.

📌 Key Points

  • API sorting controls the order of returned records.
  • Filtering decides which records are returned.
  • ORDER BY is used in SQL for sorting.
  • ASC means ascending order.
  • DESC means descending order.
  • Sorting can be performed by name, ID, fee, date, or other allowed columns.
  • Dynamic sort columns should be validated with an allowlist.
  • Prepared statement placeholders should not be used as direct SQL column identifiers.
  • Sorting can be combined with search and filtering.
  • React Native can request sorting using Fetch or Axios.
  • Sorting should be applied consistently when pagination is used.
  • Sort parameters should be validated before building the SQL query.
  • The next lesson will cover API pagination.

🧠 Quick Quiz

Question: Which SQL clause is used to sort records?