Lesson 77 of 158 – API Search
77%

API Search

API search allows a mobile application to request only the records that match a particular search term. Instead of downloading every record, the React Native application sends a search value to the REST API and the server returns matching data.

Note: Search is usually implemented using query parameters such as ?search=rahul. The API receives the search value, validates it, safely queries the database, and returns JSON data.

1. What is API Search?

API search means finding records from a server according to a value provided by the client.

Mobile App
    ↓
Search Keyword
    ↓
REST API
    ↓
Database
    ↓
Matching Records
    ↓
JSON Response
    ↓
Mobile App

2. Why Do We Need API Search?

Suppose a student management application contains 10,000 students. Downloading all students just to find one student is inefficient.

Instead, the mobile application can send:

search=rahul

The server returns only the matching students.

3. Search Using Query Parameters

A common REST API search URL looks like:

GET /api/students.php?search=rahul

Here:

  • students.php is the API endpoint.
  • search is the query parameter.
  • rahul is the search value.

4. Search Flow

User enters:
"rahul"

        ↓

React Native

        ↓

GET /api/students.php?search=rahul

        ↓

PHP REST API

        ↓

MySQL Database

        ↓

Matching Students

        ↓

JSON Response

5. Read Search Value in PHP

PHP can read the search value from the $_GET array.

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

$search = trim($search);

The null coalescing operator prevents an undefined index notice when the parameter is not supplied.

6. Check Whether Search Exists

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

if ($search === '') {

    echo json_encode([
        "success" => false,
        "message" =>
            "Search keyword is required"
    ]);

    exit;
}

The API can require a search value before executing the database query.

7. Search Students by Name

Suppose the database contains a students table with a name column.

SELECT *
FROM students
WHERE name LIKE ?

The SQL LIKE operator can be used for partial matching.

8. Using the LIKE Operator

The percent symbol % represents zero or more characters.

SELECT *
FROM students
WHERE name LIKE '%rahul%'

This can match names containing rahul.

9. Prepared Statement for Search

Use prepared statements instead of directly inserting user input into SQL queries.

$sql = "
    SELECT *
    FROM students
    WHERE name LIKE ?
";

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

$keyword = "%{$search}%";

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

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

10. Search Multiple Columns

Sometimes users should be able to search by more than one field. For example, name, email, or mobile number.

SELECT *
FROM students
WHERE name LIKE ?
   OR email LIKE ?
   OR mobile LIKE ?

The same search keyword can be supplied to all three parameters.

11. Search by Student ID

Search can also be implemented for a student ID.

SELECT *
FROM students
WHERE student_id LIKE ?

For a partial student ID search:

$keyword = "%{$search}%";

12. Search by Name or Student ID

SELECT *
FROM students
WHERE name LIKE ?
   OR student_id LIKE ?

This is useful in a student management mobile application where the user may search using either a student's name or ID.

13. Return Search Results as JSON

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

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

The React Native application can read the JSON response and display the records.

14. Empty Search Result

The API should handle the case where no record matches the search.

if (count($students) === 0) {

    echo json_encode([
        "success" => true,
        "message" =>
            "No students found",
        "data" => []
    ]);

    exit;
}

Returning an empty array makes it easy for the mobile application to handle the result.

15. Complete PHP Search API

<?php

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

require_once '../db.php';

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

if ($search === '') {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" =>
            "Search keyword is required"
    ]);

    exit;
}

try {

    $sql = "
        SELECT id,
               student_id,
               name,
               email,
               mobile
        FROM students
        WHERE name LIKE ?
           OR student_id LIKE ?
        ORDER BY name ASC
    ";

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

    $keyword = "%{$search}%";

    $stmt->execute([
        $keyword,
        $keyword
    ]);

    $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. Search API URL Example

Suppose your API is running at:

http://localhost/api/students.php

To search for Rahul:

http://localhost/api/students.php?search=rahul

The server receives rahul as the search parameter.

17. Test Search API in Postman

Method: GET

GET
http://localhost/api/students.php?search=rahul

Click Send.

A successful response may look like:

{
    "success": true,
    "data": [
        {
            "id": 1,
            "student_id": "ST001",
            "name": "Rahul Kumar",
            "email": "rahul@example.com",
            "mobile": "9876543210"
        }
    ]
}

18. React Native Fetch Search

React Native can send the search keyword using Fetch.

const searchStudents = async (keyword) => {

    const response = await fetch(
        "https://example.com/api/students.php?search="
        + encodeURIComponent(keyword)
    );

    const result =
        await response.json();

    console.log(result);
};

19. Why Use encodeURIComponent()?

Search values can contain spaces and special characters. encodeURIComponent() safely encodes the value before adding it to a URL.

const keyword =
    encodeURIComponent(
        "Rahul Kumar"
    );

const url =
    "/api/students.php?search="
    + keyword;

This prevents spaces and special characters from creating an invalid query string.

20. Search Input in React Native

<TextInput
    placeholder="Search student"
    value={search}
    onChangeText={setSearch}
/>

<Button
    title="Search"
    onPress={() =>
        searchStudents(search)
    }
/>

The TextInput collects the keyword and the button starts the API request.

21. Display Search Results

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

const searchStudents = async (
    keyword
) => {

    const response = await fetch(
        "https://example.com/api/students.php?search="
        + encodeURIComponent(keyword)
    );

    const result =
        await response.json();

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

The returned array can then be displayed using a FlatList.

22. Search Results with FlatList

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

FlatList is useful when the API returns many search results.

23. Search Loading State

A loading indicator provides feedback while the API request is running.

const [loading, setLoading] =
    useState(false);

const searchStudents = async (
    keyword
) => {

    setLoading(true);

    try {

        // API request

    } finally {

        setLoading(false);
    }
};

24. Handle Search API Errors

try {

    const response = await fetch(url);

    if (!response.ok) {
        throw new Error(
            "Search request failed"
        );
    }

    const result =
        await response.json();

    setStudents(result.data || []);

} catch (error) {

    console.log(
        error.message
    );

}

The application should handle network failures and API errors instead of assuming every request succeeds.

25. Search with Axios

import axios from "axios";

const searchStudents = async (
    keyword
) => {

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

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

Axios can automatically build the query string from the params object.

26. Search with Multiple Parameters

Search can be combined with other query parameters such as course, status, or page.

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

This allows the API to provide more specific results.

27. Search and SQL Injection Prevention

Search input comes from the user and must be treated as untrusted input. Never directly concatenate it into SQL.

Unsafe:

$sql =
    "SELECT * FROM students
     WHERE name LIKE '%$search%'";

Safer:

$sql = "
    SELECT *
    FROM students
    WHERE name LIKE ?
";

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

$stmt->execute([
    "%{$search}%"
]);

Prepared statements help protect the database from SQL injection.

28. Search API with Authentication

If student data is private, the search endpoint can be protected using JWT authentication.

Authorization:
Bearer YOUR_JWT_TOKEN

The server should verify the JWT before returning protected student data.

29. Complete Mobile Search Flow

Search Input
     ↓
React Native
     ↓
encodeURIComponent()
     ↓
GET Search API
     ↓
PHP REST API
     ↓
Validate Search
     ↓
Prepared SQL Query
     ↓
MySQL
     ↓
JSON Response
     ↓
React Native
     ↓
FlatList

30. API Search Summary

API search allows a React Native application to request matching records from a PHP/MySQL REST API. Query parameters can carry the search keyword, PHP can process the value, and prepared statements can safely search the database. The API then returns the matching records as JSON.

GET /api/students.php?search=rahul

This approach is useful for student lists, user lists, products, customers, courses, and many other mobile application features.

📌 Key Points

  • API search returns records matching a search keyword.
  • Query parameters are commonly used for search.
  • PHP can read search values using $_GET.
  • The SQL LIKE operator can perform partial matching.
  • Prepared statements should be used for database searches.
  • Search can work across multiple database columns.
  • React Native can send search requests using Fetch or Axios.
  • encodeURIComponent() helps safely encode search values in URLs.
  • FlatList can display search results efficiently.
  • Loading and error states should be handled in the mobile application.
  • Search APIs can be combined with filtering and pagination.
  • Private data should be protected with authentication and authorization.
  • The next lesson will cover API filtering.

🧠 Quick Quiz

Question: Which query parameter could be used to search for a student named Rahul?