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.
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
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.
Create a PHP file for the student endpoint.
api/
students.php
This file will contain the code for our first student API.
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.
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.
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.
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.
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.
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.
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.
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.
<?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.
Client
↓
students.php
↓
database.php
↓
PDO
↓
MySQL
↓
students table
↓
PHP Array
↓
JSON Response
This is the basic flow of our first API.
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.
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"
}
]
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.
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.
A structured response can look like:
{
"success": true,
"data": [
{
"id": "1",
"name": "Rahul"
}
]
}
This type of structure is useful when building larger APIs.
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.
<?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
]);
?>
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);
}
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.
<?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"
]);
}
?>
Postman can be used to test the API.
Choose:
Method: GET
URL:
http://localhost/rest_api/api/students.php
Then click the Send button.
After sending the request in Postman, check the response body.
A successful response may look like:
{
"success": true,
"data": [
{
"id": "1",
"name": "Rahul"
}
]
}
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.
These components work together to create a useful REST API.
rest_api/
│
├── config/
│ └── database.php
│
└── api/
└── students.php
The database connection is separated from the API endpoint.
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.
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
Question: Which PHP function converts an array into JSON?