Introduction
REST APIs allow different applications to communicate and exchange data over the internet. In PHP, you can create API endpoints, send and receive JSON data, test application functionality, debug errors, and improve performance. This chapter covers practical questions to help you understand these important PHP development skills. REST APIs and Performance in PHP Practice Questions with Solutions to help you to understand the concepts.
Question 1: Create a Simple REST API in PHP
Problem Statement
Create a simple REST API that returns a list of students in JSON format. The API should provide student information when someone opens the PHP file in a browser or sends an HTTP request.
PHP Solution
File: students.php
<?php
header("Content-Type: application/json");
$students = [
[
"id" => 1,
"name" => "Rahul",
"course" => "PHP"
],
[
"id" => 2,
"name" => "Priya",
"course" => "Python"
],
[
"id" => 3,
"name" => "Amit",
"course" => "Java"
]
];
echo json_encode($students, JSON_PRETTY_PRINT);
?>
Sample Output
[
{
"id": 1,
"name": "Rahul",
"course": "PHP"
},
{
"id": 2,
"name": "Priya",
"course": "Python"
},
{
"id": 3,
"name": "Amit",
"course": "Java"
}
]
Explanation
header("Content-Type: application/json")tells the browser or API client that the response contains JSON data.- The
$studentsarray stores student information. json_encode()converts the PHP array into JSON format.JSON_PRETTY_PRINTmakes the JSON output easier to read.
A REST API commonly uses HTTP methods such as GET, POST, PUT, PATCH, and DELETE to work with resources.
Concepts Covered
- REST API basics
- JSON response
header()json_encode()- PHP arrays
Question 2: Create a REST API Using GET Method
Problem Statement
Create an API that returns the details of a particular student based on the student ID received through a GET request.
For example:
students.php?id=2
The API should return Priya’s details.
PHP Solution
File: students.php
<?php
header("Content-Type: application/json");
$students = [
1 => [
"id" => 1,
"name" => "Rahul",
"course" => "PHP"
],
2 => [
"id" => 2,
"name" => "Priya",
"course" => "Python"
],
3 => [
"id" => 3,
"name" => "Amit",
"course" => "Java"
]
];
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
if ($id === false || $id === null || $id < 1) {
http_response_code(400);
echo json_encode([
"status" => "error",
"message" => "Valid student ID is required."
]);
exit;
}
if (isset($students[$id])) {
echo json_encode([
"status" => "success",
"data" => $students[$id]
]);
} else {
http_response_code(404);
echo json_encode([
"status" => "error",
"message" => "Student not found."
]);
}
?>
Sample Output
Request:
students.php?id=2
Response:
{
"status": "success",
"data": {
"id": 2,
"name": "Priya",
"course": "Python"
}
}
If the student ID does not exist:
{
"status": "error",
"message": "Student not found."
}
Explanation
filter_input()reads the ID from the GET request and validates it as an integer.isset()checks whether the requested student exists.http_response_code(400)sends a Bad Request status for invalid input.http_response_code(404)sends a Not Found status when the student does not exist.exitstops the script after returning an error response.
Important: GET is used to retrieve information. It should not be used to create, update, or delete records.
Concepts Covered
- GET request
$_GETandfilter_input()- Input validation
- HTTP status codes
- REST API response structure
Question 3: Create a REST API Using POST Method
Problem Statement
Create an API that accepts student details through a POST request and returns a success message with the submitted information.
The API should accept the following fields:
- Student Name
- Course
PHP Solution
File: add_student.php
<?php
header("Content-Type: application/json");
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
http_response_code(405);
echo json_encode([
"status" => "error",
"message" => "Only POST requests are allowed."
]);
exit;
}
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$course = trim($_POST["course"] ?? "");
if ($name === "" || $course === "" || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(422);
echo json_encode([
"status" => "error",
"message" => "Please provide valid student details."
]);
exit;
}
http_response_code(201);
echo json_encode([
"status" => "success",
"message" => "Student details received successfully.",
"data" => [
"name" => $name,
"email" => $email,
"course" => $course
]
]);
?>
Sample Output
POST Request Data:
name = Rahul
email = rahul@gmail.com
course = PHP
Response:
{
"status": "success",
"message": "Student details received successfully.",
"data": {
"name": "Rahul",
"email": "rahul@gmail.com",
"course": "PHP"
}
}
Explanation
$_SERVER["REQUEST_METHOD"]identifies the HTTP request method.- The API accepts only POST requests.
$_POSTreads form-encoded POST data.trim()removes unnecessary spaces from the submitted values.filter_var()checks whether the email address has a valid format.- HTTP status code
201indicates that a resource has been created.
Important: This example validates and returns submitted data but does not save it permanently. To create a real student record, connect the API to a database and use a prepared statement.
For JSON request bodies, PHP developers generally read the raw request using file_get_contents("php://input") and decode it using json_decode().
Concepts Covered
- POST request
- Request method checking
- Form data handling
- Email validation
- HTTP 201 status code
Question 4: Read JSON Data From a REST API Request
Problem Statement
Create a PHP API that receives student information in JSON format instead of normal form data.
The API should accept a student’s name, email, and course and return the received information as JSON.
PHP Solution
File: json_api.php
<?php
header("Content-Type: application/json");
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
http_response_code(405);
echo json_encode([
"status" => "error",
"message" => "Only POST requests are allowed."
]);
exit;
}
$input = file_get_contents("php://input");
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
http_response_code(400);
echo json_encode([
"status" => "error",
"message" => "Invalid JSON data."
]);
exit;
}
$name = trim($data["name"] ?? "");
$email = trim($data["email"] ?? "");
$course = trim($data["course"] ?? "");
if (
$name === "" ||
$course === "" ||
!filter_var($email, FILTER_VALIDATE_EMAIL)
) {
http_response_code(422);
echo json_encode([
"status" => "error",
"message" => "Invalid student details."
]);
exit;
}
echo json_encode([
"status" => "success",
"message" => "JSON data received successfully.",
"student" => [
"name" => $name,
"email" => $email,
"course" => $course
]
]);
?>
Sample Input
HTTP Request Body:
{
"name": "Priya",
"email": "priya@gmail.com",
"course": "Python"
}
Response:
{
"status": "success",
"message": "JSON data received successfully.",
"student": {
"name": "Priya",
"email": "priya@gmail.com",
"course": "Python"
}
}
Explanation
file_get_contents("php://input")reads the raw request body.json_decode($input, true)converts JSON data into a PHP associative array.json_last_error()checks whether JSON decoding was successful.- The API validates the received student details.
json_encode()converts the response back into JSON format.
Important: When testing this API, set the request header to:
Content-Type: application/json
Concepts Covered
- JSON request body
php://inputjson_decode()json_last_error()- JSON API validation
Question 5: Create a REST API With PUT Method
Problem Statement
Create an API that updates an existing student’s course using a PUT request.
For this practice example, use a PHP array to store student records during the script execution.
PHP Solution
File: update_student.php
<?php
header("Content-Type: application/json");
$students = [
1 => [
"id" => 1,
"name" => "Rahul",
"course" => "PHP"
],
2 => [
"id" => 2,
"name" => "Priya",
"course" => "Python"
]
];
if ($_SERVER["REQUEST_METHOD"] !== "PUT") {
http_response_code(405);
echo json_encode([
"status" => "error",
"message" => "Only PUT requests are allowed."
]);
exit;
}
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
if ($id === false || $id === null || $id < 1) {
http_response_code(400);
echo json_encode([
"status" => "error",
"message" => "Valid student ID is required."
]);
exit;
}
$input = file_get_contents("php://input");
$data = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
http_response_code(400);
echo json_encode([
"status" => "error",
"message" => "Invalid JSON data."
]);
exit;
}
$course = trim($data["course"] ?? "");
if ($course === "") {
http_response_code(422);
echo json_encode([
"status" => "error",
"message" => "Course is required."
]);
exit;
}
if (!isset($students[$id])) {
http_response_code(404);
echo json_encode([
"status" => "error",
"message" => "Student not found."
]);
exit;
}
$students[$id]["course"] = $course;
echo json_encode([
"status" => "success",
"message" => "Student course updated successfully.",
"data" => $students[$id]
]);
?>
Sample Input
Request:
PUT update_student.php?id=1
JSON Body:
{
"course": "Advanced PHP"
}
Response:
{
"status": "success",
"message": "Student course updated successfully.",
"data": {
"id": 1,
"name": "Rahul",
"course": "Advanced PHP"
}
}
Explanation
- The API checks whether the request method is PUT.
- It reads the student ID from the URL.
php://inputreads the JSON request body.- The API checks whether the student exists.
- The course value is updated in the PHP array.
Important: The array is recreated every time the script runs. Therefore, this update is temporary and is not available in the next request. A real REST API should update the database using a prepared SQL statement.
PUT generally represents replacement of a resource, while PATCH is commonly used for partial updates. This example demonstrates a simple update operation.
Concepts Covered
- PUT request
- Updating API resources
- JSON request handling
- HTTP status codes
- Temporary PHP array storage
Question 6: Create a REST API With DELETE Method
Problem Statement
Create an API that deletes a student record based on the student ID received through the URL.
Use a PHP array for this demonstration.
PHP Solution
File: delete_student.php
<?php
header("Content-Type: application/json");
$students = [
1 => [
"id" => 1,
"name" => "Rahul",
"course" => "PHP"
],
2 => [
"id" => 2,
"name" => "Priya",
"course" => "Python"
],
3 => [
"id" => 3,
"name" => "Amit",
"course" => "Java"
]
];
if ($_SERVER["REQUEST_METHOD"] !== "DELETE") {
http_response_code(405);
echo json_encode([
"status" => "error",
"message" => "Only DELETE requests are allowed."
]);
exit;
}
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
if ($id === false || $id === null || $id < 1) {
http_response_code(400);
echo json_encode([
"status" => "error",
"message" => "Valid student ID is required."
]);
exit;
}
if (!isset($students[$id])) {
http_response_code(404);
echo json_encode([
"status" => "error",
"message" => "Student not found."
]);
exit;
}
$deletedStudent = $students[$id];
unset($students[$id]);
echo json_encode([
"status" => "success",
"message" => "Student deleted successfully.",
"deleted_student" => $deletedStudent
]);
?>
Sample Output
Request:
DELETE delete_student.php?id=2
Response:
{
"status": "success",
"message": "Student deleted successfully.",
"deleted_student": {
"id": 2,
"name": "Priya",
"course": "Python"
}
}
Explanation
- The API checks whether the request method is DELETE.
filter_input()validates the student ID.isset()checks whether the student exists.- The student’s information is stored in
$deletedStudent. unset()removes the student from the array.- The API returns the deleted student’s information.
Important: This deletion is temporary because the array is created again on the next request. In a real application, use a database DELETE query with a prepared statement. Also, protect deletion endpoints with authentication, authorization, and appropriate CSRF protections where relevant.
Concepts Covered
- DELETE request
unset()- Resource deletion
- HTTP 404 status
- REST API methods
Question 7: Write a PHP Unit Test Using PHPUnit
Problem Statement
Create a PHP function that calculates the total price of a product and write a PHPUnit test to check whether the function returns the correct result.
For example:
- Product Price: ₹500
- Quantity: 3
- Expected Total: ₹1500
PHP Solution
File: Product.php
<?php
function calculateTotal($price, $quantity)
{
return $price * $quantity;
}
?>
File: ProductTest.php
<?php
use PHPUnit\Framework\TestCase;
require_once "Product.php";
class ProductTest extends TestCase
{
public function testCalculateTotal()
{
$result = calculateTotal(500, 3);
$this->assertEquals(1500, $result);
}
}
?>
Run the test using:
vendor/bin/phpunit ProductTest.php
Sample Output
PHPUnit 11.x
. 1 / 1 (100%)
OK (1 test, 1 assertion)
Explanation
calculateTotal()multiplies the product price by the quantity.ProductTestextends PHPUnit’sTestCaseclass.testCalculateTotal()contains the test case.assertEquals(1500, $result)checks whether the actual result matches the expected result.- PHPUnit reports whether the test passes or fails.
Important: This example assumes PHPUnit is already installed through Composer. For PHPUnit 11, PHP 8.2 or later is required. The exact PHPUnit version and PHP version should be compatible with your project.
Concepts Covered
- Unit testing
- PHPUnit
- Test cases
assertEquals()- Automated testing
Question 8: Debug PHP Errors Using Error Reporting
Problem Statement
Create a PHP program that displays PHP errors during development. Also, write a program that uses try-catch to handle an exception without stopping the application unexpectedly.
PHP Solution
File: debugging.php
<?php
// Enable error reporting during development
error_reporting(E_ALL);
ini_set("display_errors", "1");
$number = 10;
$divisor = 0;
try {
if ($divisor === 0) {
throw new Exception("Division by zero is not allowed.");
}
$result = $number / $divisor;
echo "Result: " . $result;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
echo "\nProgram execution completed.";
?>
Sample Output
Error: Division by zero is not allowed.
Program execution completed.
Explanation
error_reporting(E_ALL)enables reporting of all PHP error levels.ini_set("display_errors", "1")displays PHP errors during development.- The program checks whether the divisor is zero.
throw new Exception()creates an exception when division is not allowed.- The
catchblock handles the exception. getMessage()returns the exception message.- The program continues after the exception is handled.
Important: Displaying errors is useful during development, but it should be disabled on production websites. Production applications should log errors using error_log() and avoid exposing file paths, database details, or other sensitive information.
Concepts Covered
- PHP error reporting
error_reporting()ini_set()- Exception handling
try-catch- Debugging
Question 9: Measure PHP Script Execution Time
Problem Statement
Create a PHP program that measures how much time a script takes to execute.
Use microtime(true) to record the starting and ending time.
PHP Solution
File: execution_time.php
<?php
$startTime = microtime(true);
// Program execution starts
$total = 0;
for ($i = 1; $i <= 1000000; $i++) {
$total += $i;
}
// Program execution ends
$endTime = microtime(true);
$executionTime = $endTime - $startTime;
echo "Total: " . $total . "<br>";
echo "Execution Time: " . $executionTime . " seconds";
?>
Sample Output
Total: 500000500000
Execution Time: 0.025 seconds
<text>Note: The execution time shown is an illustrative example. Actual time depends on the computer, PHP version, server load, and environment.</text>
Explanation
microtime(true)returns the current time as a floating-point number.$startTimestores the starting time.- The
forloop performs one million additions. $endTimestores the ending time.- Subtracting the starting time from the ending time gives the execution duration.
Important: Execution time can vary between runs. For reliable performance comparisons, run tests multiple times under similar conditions. Also consider database queries, network requests, and memory usage when measuring an application.
Concepts Covered
- PHP performance measurement
microtime()- Execution time
- Loop performance
- Basic performance testing
Question 10: Improve PHP Performance Using Array Caching
Problem Statement
A PHP application repeatedly calculates the total sales for the same department.
Create a program that stores the calculated result in an array cache. If the same department is requested again, use the stored result instead of calculating it again.
PHP Solution
File: caching.php
<?php
$sales = [
"IT" => [10000, 15000, 20000],
"HR" => [8000, 12000, 10000],
"Marketing" => [18000, 22000, 25000]
];
$cache = [];
function getDepartmentTotal($department, $sales, &$cache)
{
if (isset($cache[$department])) {
echo "Result fetched from cache.<br>";
return $cache[$department];
}
echo "Calculating department total.<br>";
$total = array_sum($sales[$department]);
$cache[$department] = $total;
return $total;
}
echo "IT Total: ";
echo getDepartmentTotal("IT", $sales, $cache);
echo "<br><br>";
echo "IT Total: ";
echo getDepartmentTotal("IT", $sales, $cache);
?>
Sample Output
IT Total: Calculating department total.
45000
IT Total: Result fetched from cache.
45000
Explanation
- The
$salesarray stores department-wise sales values. - The
$cachearray stores previously calculated totals. getDepartmentTotal()checks whether the department total already exists in the cache.isset()checks whether the cached value is available.- If the value exists, the function returns it without calculating again.
- If the value does not exist,
array_sum()calculates the total. - The calculated result is saved in
$cachefor future use. - The
&$cacheparameter passes the cache array by reference, allowing the function to update the original array.
Important: This is an in-memory cache that works only during the current PHP request. For caching across multiple requests, applications can use Redis, Memcached, or other caching systems. Cached data must also be refreshed or invalidated when the original sales data changes.
Concepts Covered
- PHP caching
- Array caching
array_sum()- Pass by reference
- Performance optimization
- Avoiding repeated calculations
Key Takeaways
- REST APIs allow applications to exchange information using HTTP requests.
- GET retrieves resources, POST creates resources, PUT replaces resources, PATCH partially updates resources, and DELETE removes resources.
- JSON is a common format for sending and receiving API data.
json_encode()converts PHP data into JSON.json_decode()converts JSON into PHP data.- HTTP status codes communicate the result of API requests.
- PHPUnit helps developers test PHP functions automatically.
- Error reporting and exception handling help identify and manage application problems.
microtime(true)helps measure script execution time.- Caching can reduce repeated calculations and improve performance.
Frequently Asked Questions (FAQs)
1. What is a REST API in PHP?
A REST API in PHP is an interface that allows different applications to communicate using HTTP requests. PHP can receive requests, process data, interact with databases, and return responses, commonly in JSON format.
2. What are the main HTTP methods used in REST APIs?
The main HTTP methods are GET, POST, PUT, PATCH, and DELETE. They are commonly used to retrieve, create, replace, partially update, and delete resources.
3. What is JSON in PHP?
JSON stands for JavaScript Object Notation. It is a lightweight data format used to exchange information between applications. PHP provides json_encode() and json_decode() to work with JSON data.
4. What is the difference between GET and POST in PHP?
GET sends data through the URL query string and is commonly used to retrieve information. POST sends data in the request body and is commonly used to submit or create information.
5. What is PHPUnit in PHP?
PHPUnit is a testing framework used to test PHP code automatically. It helps developers check whether functions and application components produce the expected results.
6. What is unit testing in PHP?
Unit testing means testing a small individual part of a program, such as a function or method, to verify that it works correctly.
7. How can we debug PHP code?
Developers can debug PHP code using error reporting, exception handling, error logs, debugging tools, and IDE features. During development, error_reporting(E_ALL) helps identify errors.
8. What is the purpose of microtime() in PHP?
microtime() returns the current time with microsecond precision. Developers can use microtime(true) to measure how long a PHP script or operation takes to execute.
9. What is caching in PHP?
Caching means storing previously calculated or retrieved data so that it can be reused instead of performing the same operation repeatedly. It can reduce processing time and improve application performance.
10. How can we improve PHP application performance?
PHP performance can be improved by optimizing database queries, using appropriate indexes, caching repeated results, avoiding unnecessary loops, reducing memory usage, and profiling slow operations.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
