A REST API allows different applications to communicate using HTTP requests. For example, a JavaScript frontend can request student records from a PHP backend and receive the data in JSON format.
In this lesson, you will learn REST API basics, HTTP methods, JSON responses, request handling, database integration, and API security using PHP.
REST stands for Representational State Transfer. A REST-style API exposes resources through URLs and uses HTTP methods to perform operations.
For a student management system, example endpoints are:
GET /api/students.php
GET /api/students.php?id=5
POST /api/students.php
PUT /api/students.php?id=5
PATCH /api/students.php?id=5
DELETE /api/students.php?id=5
Common HTTP methods:
REST is an architectural style. A practical API should use appropriate HTTP methods, status codes, resource URLs, and consistent response formats.
Create a folder named api inside your
project and create a file named
hello.php.
File: api/hello.php
<?php
header("Content-Type: application/json; charset=UTF-8");
$response = [
"success" => true,
"message" => "Welcome to PHP REST API",
"language" => "PHP"
];
echo json_encode($response);
?>
Open this endpoint through your local server, for example:
http://localhost/your_project/api/hello.php
Expected JSON response:
{
"success": true,
"message": "Welcome to PHP REST API",
"language": "PHP"
}
The header() function sets the response
content type. The json_encode() function
converts a PHP array into JSON.
GET requests are commonly used to retrieve information. The following example returns student data from a PHP array without connecting to a database.
File: api/students.php
<?php
header("Content-Type: application/json; charset=UTF-8");
$students = [
[
"id" => 1,
"name" => "Rahul",
"course" => "PHP"
],
[
"id" => 2,
"name" => "Priya",
"course" => "JavaScript"
],
[
"id" => 3,
"name" => "Amit",
"course" => "Python"
]
];
if (isset($_GET["id"])) {
$id = filter_var(
$_GET["id"],
FILTER_VALIDATE_INT
);
if ($id === false || $id === null || $id < 1) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid student ID"
]);
exit;
}
foreach ($students as $student) {
if ($student["id"] === $id) {
echo json_encode($student);
exit;
}
}
http_response_code(404);
echo json_encode([
"success" => false,
"message" => "Student not found"
]);
exit;
}
echo json_encode($students);
?>
Example URLs:
GET /api/students.php
GET /api/students.php?id=2
The first URL returns all sample students. The second returns the student whose ID is 2.
This is demonstration data. A real application would normally retrieve records from a database.
POST requests are commonly used to create resources. APIs often receive JSON request bodies rather than ordinary HTML form fields.
Example: Read JSON input
<?php
header("Content-Type: application/json; charset=UTF-8");
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
header("Allow: POST");
http_response_code(405);
echo json_encode([
"success" => false,
"message" => "Method not allowed"
]);
exit;
}
$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);
if (
json_last_error() !== JSON_ERROR_NONE ||
!is_array($data)
) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" => "Invalid JSON"
]);
exit;
}
$name = trim($data["name"] ?? "");
$course = trim($data["course"] ?? "");
if ($name === "" || $course === "") {
http_response_code(422);
echo json_encode([
"success" => false,
"message" => "Name and course are required"
]);
exit;
}
http_response_code(201);
echo json_encode([
"success" => true,
"message" => "Student data validated",
"student" => [
"name" => $name,
"course" => $course
]
]);
?>
Example JSON request body:
{
"name": "Rohit",
"course": "PHP"
}
Send the request with the
Content-Type: application/json header.
This example validates the data but does not save it
permanently.
A database allows the API to retrieve and store persistent information. Use PDO and prepared statements when working with user-supplied values.
Example database table:
CREATE DATABASE php_api_db;
USE php_api_db;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
course VARCHAR(100) NOT NULL
);
File: api/db.php
<?php
$host = "localhost";
$dbname = "php_api_db";
$username = "YOUR_DB_USERNAME";
$password = "YOUR_DB_PASSWORD";
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
]
);
?>
Replace the database credentials with your actual credentials. Keep them outside publicly accessible files and do not expose them in API responses.
Example: Retrieve students from MySQL
<?php
header("Content-Type: application/json; charset=UTF-8");
try {
require __DIR__ . "/db.php";
$stmt = $pdo->query(
"SELECT id, name, course
FROM students
ORDER BY id DESC"
);
echo json_encode([
"success" => true,
"data" => $stmt->fetchAll()
]);
} catch (PDOException $e) {
error_log($e->getMessage());
http_response_code(500);
echo json_encode([
"success" => false,
"message" => "Internal server error"
]);
}
?>
This endpoint retrieves all students from MySQL. In a production application, consider pagination, authorization, and appropriate access restrictions.
HTTP status codes communicate the result of an API request to the client.
| Status | Meaning | Example |
|---|---|---|
| 200 | OK | Student retrieved |
| 201 | Created | Student created |
| 204 | No Content | Successful deletion with no response body |
| 400 | Bad Request | Malformed JSON or invalid request |
| 401 | Unauthorized | Authentication is required or invalid |
| 403 | Forbidden | User lacks permission |
| 404 | Not Found | Student does not exist |
| 405 | Method Not Allowed | Unsupported HTTP method |
| 422 | Unprocessable Content | Validation failed |
| 500 | Internal Server Error | Unexpected server failure |
PHP example:
<?php
header("Content-Type: application/json; charset=UTF-8");
http_response_code(404);
echo json_encode([
"success" => false,
"message" => "Student not found"
]);
?>
Use an appropriate status code and a consistent JSON response structure. Do not return internal stack traces, SQL queries, or database credentials to clients.
JavaScript's fetch() function can request
data from a PHP API and display the returned JSON.
Example HTML and JavaScript:
<button id="loadStudents">
Load Students
</button>
<ul id="studentList"></ul>
<script>
document.getElementById("loadStudents")
.addEventListener("click", async function () {
const list = document.getElementById("studentList");
list.textContent = "Loading...";
try {
const response = await fetch(
"api/students.php"
);
if (!response.ok) {
throw new Error("API request failed");
}
const students = await response.json();
list.replaceChildren();
students.forEach(function (student) {
const item = document.createElement("li");
item.textContent =
student.name + " - " + student.course;
list.appendChild(item);
});
} catch (error) {
list.textContent =
"Unable to load students.";
}
});
</script>
The example assumes that
api/students.php returns the sample array
shown in Lesson 3.
Using textContent instead of inserting
untrusted values with innerHTML helps
prevent client-side HTML injection.
If the frontend and API are hosted on different origins, configure CORS on the API for the specific origins that should be allowed. CORS is not an authentication system.
APIs may expose private student, employee, or payment information. Protect endpoints before allowing access to sensitive data or modifying records.
Example: Check for an authenticated session
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
if (!isset($_SESSION["user_id"])) {
http_response_code(401);
echo json_encode([
"success" => false,
"message" => "Authentication required"
]);
exit;
}
// Check the user's permissions before accessing
// or changing any protected resource.
?>
This is a basic session-based check, not a complete API authentication system. A mobile app or separate frontend may need a properly implemented token-based authentication approach.
For cookie-based authentication, protect state-changing requests against CSRF. Never assume that hiding a URL or knowing a student ID grants permission to access that student's data.
Create a small PHP REST API for managing students. Use PHP, MySQL, PDO, and JSON responses.
Requirements:
php_api_db.students table with ID, name, and course fields.api/db.php for the PDO connection.api/students.php to return all students using GET.Suggested project structure:
php_rest_api/
|
|-- api/
| |-- db.php
| |-- students.php
| |-- hello.php
|
|-- index.html
|
|-- database.sql
Test GET, POST, invalid input, missing records, and database errors using a REST client such as Postman. Test authorization before implementing update and delete operations.
Learning goal: Build an API that returns structured JSON, interacts safely with MySQL, and validates requests correctly.
1. Which HTTP method is commonly used to retrieve data?
2. Which PHP function converts a PHP array into JSON?
3. What should you use to safely insert user values into SQL queries?