Lesson 53 of 158 – First PHP REST API
53%

First PHP REST API

Now that our MySQL database, tables, and PDO connection are ready, we can create our first PHP REST API. In this lesson, we will build a simple API that connects to MySQL and returns student data as JSON.

Note: Our first API will focus on reading student records. We will keep the API simple so that you understand the complete flow from PHP to MySQL to JSON.

1. What is Our First API?

Our first API will be a PHP endpoint that communicates with the students table in the student_api database.

Mobile App
    ↓
PHP REST API
    ↓
MySQL
    ↓
students table

2. API Endpoint

An API endpoint is a URL through which a client communicates with the server.

For example:

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

When this URL is requested, the PHP file can process the request and return a response.

3. Create the API File

Create a PHP file for the student endpoint.

api/
    students.php

This file will contain the code for our first student API.

4. Include the Database Connection

The API needs access to the database. We can include our reusable PDO connection file.

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

After including the file, the $pdo variable can be used for database operations.

5. Set the Response Content Type

Our API will return JSON data, so we should tell the client that the response contains JSON.

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

This is an important header for a JSON REST API.

6. First API Code

A simple starting API can look like this:

<?php

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

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

echo json_encode([
    "message" => "API is working"
]);

?>

This API does not access the database yet. It simply returns a JSON response.

7. What is JSON?

JSON stands for JavaScript Object Notation. REST APIs commonly use JSON to exchange data between clients and servers.

{
    "message": "API is working"
}

A React Native application can easily read this response.

8. Test the API in a Browser

For a simple GET endpoint, you can enter the API URL into a browser.

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

If the API is working, the browser should display the JSON response.

9. Connect the API to MySQL

Now we can use the PDO connection to retrieve data from MySQL.

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

The SQL query selects all records from the students table.

10. Fetch the Records

After executing the query, we can fetch all records as an array.

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

Each database row becomes an associative array.

11. Return Student Data as JSON

The PHP array can be converted into JSON using json_encode().

echo json_encode($students);

This allows the client application to receive the database records as JSON.

12. Complete Basic GET 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 is a simple working GET API for reading student records.

13. API Request Flow

Client
  ↓
students.php
  ↓
database.php
  ↓
PDO
  ↓
MySQL
  ↓
students table
  ↓
PHP Array
  ↓
JSON Response

This is the basic flow of our first API.

14. HTTP GET Request

When a client requests student information without sending a new record, the API can use the HTTP GET method.

GET /api/students.php

The API reads the student records and returns them.

15. API Response Example

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

[
    {
        "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"
    }
]

16. Empty Table Response

If the students table does not contain any records, the API may return an empty JSON array.

[]

An empty array is valid JSON and tells the client that no student records were found.

17. Use a Response Object

Instead of returning only the array, we can create a structured response.

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

echo json_encode($response);

This structure gives the client additional information about the request.

18. API Response Structure

A structured response can look like:

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

This type of structure is useful when building larger APIs.

19. Set HTTP Status Code

PHP can set the HTTP status code of an API response.

http_response_code(200);

Status code 200 generally means that the request was successful.

20. Basic API with Status Code

<?php

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

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

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

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

http_response_code(200);

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

?>

21. Handle Database Errors

Database operations can fail. We can use a try-catch block around the database operation.

try {

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

} catch (PDOException $e) {

    http_response_code(500);

}

22. Return an Error Response

When a database error occurs, the API can return a JSON error response.

http_response_code(500);

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

The mobile application can use this response to display an appropriate message.

23. Complete API with Error Handling

<?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,
        "data" => $students
    ]);

} catch (PDOException $e) {

    http_response_code(500);

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

}

?>

24. Test with Postman

Postman can be used to test the API.

Choose:

Method: GET

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

Then click the Send button.

25. Check the Response

After sending the request in Postman, check the response body.

A successful response may look like:

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

26. Test from React Native

The same API can later be requested from a React Native application using the Fetch API.

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

The exact URL used on a physical device or emulator may be different from localhost.

27. Important API Components

  • API endpoint
  • HTTP method
  • Request headers
  • PHP code
  • PDO database connection
  • SQL query
  • JSON response
  • HTTP status code

These components work together to create a useful REST API.

28. First API Project Structure

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

The database connection is separated from the API endpoint.

29. Complete First REST API Flow

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

This is the basic pattern we will use to build more advanced API endpoints.

30. First PHP REST API Summary

We created our first PHP REST API endpoint. The endpoint connects to MySQL using PDO, retrieves student records from the students table, and returns the data as JSON. This is the foundation for the CRUD APIs we will create in the following lessons.

React Native
      ↓
GET Request
      ↓
PHP REST API
      ↓
PDO + MySQL
      ↓
students
      ↓
JSON Response

📌 Key Points

  • A REST API provides an endpoint for client-server communication.
  • Our first API is a PHP student endpoint.
  • The API uses the HTTP GET method to read student data.
  • PDO connects PHP to the MySQL database.
  • The students table contains the student records.
  • SELECT * FROM students retrieves student records.
  • fetchAll(PDO::FETCH_ASSOC) converts database rows into an array.
  • json_encode() converts PHP data into JSON.
  • Content-Type: application/json identifies the response format.
  • HTTP status code 200 represents a successful request.
  • Postman can be used to test the API.
  • React Native can consume the same API using Fetch or Axios.

🧠 Quick Quiz

Question: Which PHP function converts an array into JSON?