REST APIs and Performance in PHP Practice Questions with Solutions

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

  1. header("Content-Type: application/json") tells the browser or API client that the response contains JSON data.
  2. The $students array stores student information.
  3. json_encode() converts the PHP array into JSON format.
  4. JSON_PRETTY_PRINT makes 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

  1. filter_input() reads the ID from the GET request and validates it as an integer.
  2. isset() checks whether the requested student exists.
  3. http_response_code(400) sends a Bad Request status for invalid input.
  4. http_response_code(404) sends a Not Found status when the student does not exist.
  5. exit stops 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
  • $_GET and filter_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
  • Email
  • 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

  1. $_SERVER["REQUEST_METHOD"] identifies the HTTP request method.
  2. The API accepts only POST requests.
  3. $_POST reads form-encoded POST data.
  4. trim() removes unnecessary spaces from the submitted values.
  5. filter_var() checks whether the email address has a valid format.
  6. HTTP status code 201 indicates 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

  1. file_get_contents("php://input") reads the raw request body.
  2. json_decode($input, true) converts JSON data into a PHP associative array.
  3. json_last_error() checks whether JSON decoding was successful.
  4. The API validates the received student details.
  5. 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://input
  • json_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

  1. The API checks whether the request method is PUT.
  2. It reads the student ID from the URL.
  3. php://input reads the JSON request body.
  4. The API checks whether the student exists.
  5. 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

  1. The API checks whether the request method is DELETE.
  2. filter_input() validates the student ID.
  3. isset() checks whether the student exists.
  4. The student’s information is stored in $deletedStudent.
  5. unset() removes the student from the array.
  6. 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

  1. calculateTotal() multiplies the product price by the quantity.
  2. ProductTest extends PHPUnit’s TestCase class.
  3. testCalculateTotal() contains the test case.
  4. assertEquals(1500, $result) checks whether the actual result matches the expected result.
  5. 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

  1. error_reporting(E_ALL) enables reporting of all PHP error levels.
  2. ini_set("display_errors", "1") displays PHP errors during development.
  3. The program checks whether the divisor is zero.
  4. throw new Exception() creates an exception when division is not allowed.
  5. The catch block handles the exception.
  6. getMessage() returns the exception message.
  7. 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

  1. microtime(true) returns the current time as a floating-point number.
  2. $startTime stores the starting time.
  3. The for loop performs one million additions.
  4. $endTime stores the ending time.
  5. 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

  1. The $sales array stores department-wise sales values.
  2. The $cache array stores previously calculated totals.
  3. getDepartmentTotal() checks whether the department total already exists in the cache.
  4. isset() checks whether the cached value is available.
  5. If the value exists, the function returns it without calculating again.
  6. If the value does not exist, array_sum() calculates the total.
  7. The calculated result is saved in $cache for future use.
  8. The &$cache parameter 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.

Scroll to Top