Lesson 54 of 158 – Get All Records API
54%

Get All Records API

In the previous lesson, we created our first PHP REST API. Now we will create a proper GET API that retrieves all student records from the MySQL students table and returns them as JSON.

Note: The GET All Records API is used when the client wants to retrieve multiple records from the database.

1. What is a Get All API?

A Get All API retrieves all available records from a database table.

For our project, the endpoint will retrieve all students.

GET /api/students.php

The response will contain multiple student records.

2. GET HTTP Method

The HTTP GET method is commonly used to retrieve data from a server.

GET /api/students.php

The client sends a request and the server returns the requested data.

3. API Endpoint

Our student API endpoint can be:

http://localhost/rest_api/api/students.php

When a GET request is sent to this URL, the PHP file will retrieve the student records.

4. Include Database Connection

The API needs a database connection before it can execute a SQL query.

require_once "../config/database.php";

The included file provides the PDO connection stored in $pdo.

5. Set JSON Response Header

Our API returns JSON, so we should set the response content type.

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

This tells the client that the response is JSON data.

6. SELECT All Records

The SQL SELECT statement is used to retrieve records.

SELECT * FROM students

The * means that all columns should be selected.

7. Execute the Query

Using PDO, we can execute the SELECT query.

$stmt = $pdo->query(
    "SELECT * FROM students"
);

The result is stored in the $stmt variable.

8. Fetch All Records

The fetchAll() method can retrieve all rows returned by the query.

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

Each row is returned as an associative array.

9. PDO::FETCH_ASSOC

PDO::FETCH_ASSOC tells PDO to return each database row as an associative array using column names as keys.

[
    "id" => 1,
    "name" => "Rahul",
    "email" => "rahul@example.com"
]

10. Convert Data to JSON

After fetching the records, convert the PHP array into JSON.

echo json_encode($students);

The JSON response can then be consumed by Postman, React Native, or another client.

11. Basic Get All API

<?php

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

require_once "../config/database.php";

$stmt = $pdo->query(
    "SELECT * FROM students"
);

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

echo json_encode($students);

?>

This API retrieves all student records.

12. Structured API Response

A better API response can contain a success status and data.

$response = [
    "success" => true,
    "data" => $students
];

echo json_encode($response);

13. Example JSON Response

If the database contains two students, the API may return:

{
    "success": true,
    "data": [
        {
            "id": "1",
            "name": "Rahul",
            "email": "rahul@example.com",
            "mobile": "9876543210",
            "course": "PHP"
        },
        {
            "id": "2",
            "name": "Amit",
            "email": "amit@example.com",
            "mobile": "9876501234",
            "course": "React Native"
        }
    ]
}

14. HTTP Status Code 200

A successful GET request can return HTTP status code 200 OK.

http_response_code(200);

The client can use the status code to determine whether the request was successful.

15. Add Status Code to API

http_response_code(200);

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

This explicitly tells the client that the request was successful.

16. Empty Result

If there are no students in the table, fetchAll() returns an empty array.

[]

The API can still return a successful response because the request itself was processed successfully.

17. Count the Records

We can count the number of retrieved records using PHP's count() function.

$total = count($students);

The total can be included in the API response.

18. Add Total to Response

$response = [
    "success" => true,
    "total" => count($students),
    "data" => $students
];

echo json_encode($response);

This response tells the client how many records were returned.

19. Handle Database Errors

A database query can fail. We should handle possible PDO exceptions.

try {

    $stmt = $pdo->query(
        "SELECT * FROM students"
    );

} catch (PDOException $e) {

    http_response_code(500);

}

20. Return Error JSON

When the database operation fails, the API can return a JSON error.

http_response_code(500);

echo json_encode([
    "success" => false,
    "message" => "Failed to fetch students"
]);

The client can use this response to display an appropriate message.

21. Complete Get All API

<?php

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

require_once "../config/database.php";

try {

    $stmt = $pdo->query(
        "SELECT * FROM students"
    );

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

    http_response_code(200);

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

} catch (PDOException $e) {

    http_response_code(500);

    echo json_encode([
        "success" => false,
        "message" => "Failed to fetch students"
    ]);

}

?>

22. Test the API in Postman

Open Postman and create a GET request.

Method:
GET

URL:
http://localhost/rest_api/api/students.php

Click Send to execute the request.

23. Check the Status

After sending the request, check the HTTP status displayed by Postman.

200 OK

A 200 status indicates that the request was successfully processed.

24. Check the JSON Body

The response body should contain the student data.

{
    "success": true,
    "total": 2,
    "data": [
        {
            "id": "1",
            "name": "Rahul"
        },
        {
            "id": "2",
            "name": "Amit"
        }
    ]
}

25. Get All API Flow

GET Request
     ↓
students.php
     ↓
PDO Connection
     ↓
SELECT * FROM students
     ↓
fetchAll()
     ↓
PHP Array
     ↓
json_encode()
     ↓
JSON Response

26. React Native Client

A React Native application can request the same API using Fetch.

fetch("http://localhost/rest_api/api/students.php")
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

Later we will learn how to display this data inside React Native components.

27. Why Get All is Important

A Get All API is useful for displaying lists of records in applications.

Examples include:

  • Student list
  • Product list
  • Course list
  • User list
  • Order list

28. Important Security Point

Do not automatically expose sensitive database columns through a public GET API.

For example, passwords should never be returned in a normal student list response.

SELECT id, name, email, mobile, course
FROM students;

Selecting only the required columns is often better than exposing every column.

29. Get All API Project Structure

rest_api/
│
├── config/
│   └── database.php
│
└── api/
    └── students.php

The database connection is reusable while the students endpoint contains the API-specific logic.

30. Get All Records Summary

The Get All Records API retrieves multiple student records from MySQL and returns them as JSON. The API uses a GET request, PDO for database access, a SELECT query for retrieving records, and json_encode() for creating the JSON response.

GET
 ↓
SELECT
 ↓
fetchAll()
 ↓
json_encode()
 ↓
JSON Response

📌 Key Points

  • The GET method is used to retrieve data.
  • A Get All API retrieves multiple records.
  • SELECT * FROM students retrieves student records.
  • fetchAll(PDO::FETCH_ASSOC) retrieves all rows as associative arrays.
  • json_encode() converts PHP data into JSON.
  • HTTP status code 200 represents a successful request.
  • An empty table can return an empty array.
  • count() can be used to calculate the number of records.
  • PDO exceptions can be handled using try-catch.
  • Postman can be used to test the Get All API.
  • React Native can consume the API using Fetch or Axios.
  • A public API should not expose sensitive database columns.

🧠 Quick Quiz

Question: Which SQL query is used to retrieve all records from the students table?