Lesson 78 of 158 – API Filtering
78%

API Filtering

API filtering allows a mobile application to request only the records that match specific conditions. Instead of returning every record, the REST API applies one or more filters and returns the required data.

Note: Search and filtering are related but different. Search usually looks for a keyword, while filtering selects records according to specific conditions such as course, status, category, price, date, or user ID.

1. What is API Filtering?

API filtering means selecting only the records that satisfy a particular condition.

Mobile App
    ↓
Filter Parameters
    ↓
REST API
    ↓
Database
    ↓
Filtered Records
    ↓
JSON Response

2. Why Do We Need Filtering?

Suppose a student database contains 5,000 students. A mobile application may need only active students.

Instead of downloading all 5,000 students, the application can request:

?status=active

The server returns only active students.

3. Filtering Using Query Parameters

A common filtering URL is:

GET /api/students.php?status=active

Here status is the filter parameter and active is its value.

4. Search vs Filtering

Search Filtering
Looks for a keyword Selects records using conditions
Example: search=rahul Example: status=active
Usually text based Can use text, numbers, dates, categories, etc.

5. Read Filter Value in PHP

$status = trim(
    $_GET['status'] ?? ''
);

The API can read the filter value from the query string using $_GET.

6. Filter Students by Status

Suppose the students table contains a status column.

SELECT *
FROM students
WHERE status = ?

The value can be supplied safely using a prepared statement.

7. Prepared Statement for Filtering

$sql = "
    SELECT *
    FROM students
    WHERE status = ?
";

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

$stmt->execute([
    $status
]);

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

Prepared statements help keep user-provided filter values separate from SQL commands.

8. Filter by Course

Suppose students have a course column.

GET /api/students.php?course=PHP

The SQL condition can be:

SELECT *
FROM students
WHERE course = ?

9. Filter by Class

Filtering can also be used for a class or category.

GET /api/students.php?class=12

PHP can read the value:

$class = $_GET['class'] ?? '';

$stmt = $pdo->prepare(
    "SELECT *
     FROM students
     WHERE class = ?"
);

$stmt->execute([$class]);

10. Filter by User ID

An API can return records belonging to a specific user.

GET /api/orders.php?user_id=15

The SQL query could be:

SELECT *
FROM orders
WHERE user_id = ?

11. Numeric Filtering

Filtering can also be performed using numeric values.

For example, find products below a particular price:

GET /api/products.php?max_price=1000
SELECT *
FROM products
WHERE price <= ?

12. Minimum Value Filter

You can also filter records using a minimum value.

GET /api/products.php?min_price=500
SELECT *
FROM products
WHERE price >= ?

13. Date Filtering

Date filters are useful for payments, orders, attendance, reports, and other time-based records.

GET /api/payments.php?date=2026-10-04

Example SQL:

SELECT *
FROM payments
WHERE payment_date = ?

14. Multiple Filters

An API can receive more than one filter at the same time.

GET /api/students.php
    ?course=PHP
    &status=active

The SQL query can use AND:

SELECT *
FROM students
WHERE course = ?
  AND status = ?

15. Complete PHP Filtering API

<?php

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

require_once '../db.php';

$status =
    trim($_GET['status'] ?? '');

$course =
    trim($_GET['course'] ?? '');

if (
    $status === '' &&
    $course === ''
) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "At least one filter is required"
    ]);

    exit;
}

try {

    $conditions = [];
    $params = [];

    if ($status !== '') {

        $conditions[] =
            "status = ?";

        $params[] = $status;
    }

    if ($course !== '') {

        $conditions[] =
            "course = ?";

        $params[] = $course;
    }

    $sql = "
        SELECT id,
               student_id,
               name,
               course,
               status
        FROM students
        WHERE "
        . implode(
            " AND ",
            $conditions
        )
        . "
        ORDER BY name ASC
    ";

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

    $stmt->execute($params);

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

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

} catch (PDOException $e) {

    http_response_code(500);

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

?>

16. Filter API URL Example

Suppose we want active PHP students:

http://localhost/api/students.php
?course=PHP&status=active

The API applies both conditions and returns students satisfying both filters.

17. Filtering with OR

Sometimes an API needs records matching either of two conditions.

SELECT *
FROM students
WHERE course = ?
   OR course = ?

For example, the API could return students from either PHP or Java.

18. Filtering with IN

The SQL IN operator can be useful when selecting from multiple known values.

SELECT *
FROM students
WHERE course IN ('PHP', 'Java', 'Python')

For dynamic values, generate placeholders and bind them safely instead of directly inserting user input.

19. Filtering with Boolean Values

Some tables contain boolean-like values such as active/inactive or published/unpublished.

GET /api/courses.php?published=1

Example query:

SELECT *
FROM courses
WHERE published = ?

The API should validate the expected values before executing the query.

20. Filtering in React Native

React Native can send filter values as query parameters.

const response = await fetch(
    "https://example.com/api/students.php"
    + "?course=PHP"
    + "&status=active"
);

const result =
    await response.json();

console.log(result.data);

21. Filtering with Axios

import axios from "axios";

const response = await axios.get(
    "https://example.com/api/students.php",
    {
        params: {
            course: "PHP",
            status: "active"
        }
    }
);

console.log(
    response.data.data
);

Axios creates the query string from the params object.

22. Filter Selection in React Native

A mobile application can provide controls such as dropdowns or buttons for selecting filters.

const [course, setCourse] =
    useState("PHP");

const [status, setStatus] =
    useState("active");

The selected values can then be sent to the filtering API.

23. Filter and Display Results

const [students, setStudents] =
    useState([]);

const loadStudents = async () => {

    const response = await axios.get(
        "https://example.com/api/students.php",
        {
            params: {
                course,
                status
            }
        }
    );

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

The returned records can be displayed using a FlatList.

24. Filter with Search

Search and filtering can be combined.

GET /api/students.php
    ?search=rahul
    &course=PHP
    &status=active

The API can apply the keyword search together with the selected filters.

WHERE
    (
        name LIKE ?
        OR student_id LIKE ?
    )
AND course = ?
AND status = ?

25. Validate Filter Values

Never assume that a filter value supplied by a user is valid.

$allowedStatus = [
    'active',
    'inactive'
];

if (
    $status !== '' &&
    !in_array(
        $status,
        $allowedStatus,
        true
    )
) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Invalid status"
    ]);

    exit;
}

26. Filtering and SQL Injection

Filter values come from the client and should be treated as untrusted input.

Unsafe:

$sql =
    "SELECT * FROM students
     WHERE status = '$status'";

Safer:

$stmt = $pdo->prepare(
    "SELECT *
     FROM students
     WHERE status = ?"
);

$stmt->execute([
    $status
]);

Prepared statements should be used for dynamic values.

27. Filtering with Authentication

If the API returns private data, filtering should be performed only after authentication and authorization checks where required.

Authorization:
Bearer YOUR_JWT_TOKEN

For example, a student should normally receive only data they are authorized to access.

28. Test Filtering API in Postman

Method: GET

http://localhost/api/students.php
?course=PHP&status=active

Click Send.

Example response:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "student_id": "ST001",
            "name": "Rahul Kumar",
            "course": "PHP",
            "status": "active"
        }
    ]
}

29. Complete Filtering Flow

React Native
     ↓
Select Filters
     ↓
Query Parameters
     ↓
GET Request
     ↓
PHP REST API
     ↓
Validate Filters
     ↓
Build Conditions
     ↓
Prepared SQL Query
     ↓
MySQL
     ↓
Filtered JSON Data
     ↓
React Native FlatList

30. API Filtering Summary

API filtering allows a React Native application to request only the records that satisfy selected conditions. PHP receives the filter parameters, validates them, creates the required SQL conditions, and uses prepared statements to safely retrieve the matching records.

GET /api/students.php
?course=PHP&status=active

Filtering is an important REST API feature for student management, e-commerce, attendance, payment, product, and many other mobile applications.

📌 Key Points

  • API filtering selects records according to specific conditions.
  • Query parameters are commonly used to send filter values.
  • Filtering can be performed by status, course, category, date, price, user ID, and more.
  • Multiple filters can be combined using SQL AND.
  • SQL OR can be used when either condition should match.
  • Filter values should always be validated.
  • Prepared statements should be used for dynamic database values.
  • Search and filtering can be combined in one API.
  • React Native can send filters using Fetch or Axios.
  • Filtered results can be displayed using FlatList.
  • Private filtering APIs should use authentication and authorization.
  • The next lesson will cover API sorting.

🧠 Quick Quiz

Question: Which URL correctly filters students by active status?