Example of a REST API in PHP from Scratch (Without Using a Framework)

Публикувано на 04.09.2018
Example of a REST API in PHP from Scratch (Without Using a Framework)

Introduction

Before we move on to the practical part, let’s first explain in simple terms what REST API is and why it’s so important in modern web development.


What is REST API

REST (Representational State Transfer) is an architectural style used for building web services. In simple terms, it’s a concept for accessing and modifying resources based on the interaction between a client and a server. The client sends a request, the server processes it, and returns a response according to the parameters received.

The REST architecture follows six core principles, and when an application meets them, it is considered RESTful.

API (Application Programming Interface) is a set of rules and methods that allow different software components to communicate with each other.

A RESTful API is a web application built upon the principles of REST and HTTP. It usually exchanges data in JSON format but can also work with other types. The main supported methods are GET, POST, PUT, and DELETE.


What is REST API used for

Example 1: Suppose we have an online business and want to track monthly visits. Instead of opening Google Analytics every time, we can use its API via Google Developers. This way, analytics data will appear directly inside our own dashboard.

Example 2: We work with a library management software that handles books and readers. The application is hosted at lib.example.com and contains a complete bibliographic database. Thanks to the REST API architecture, the data can be shared between the library website and the connected school websites.

In this way, multiple applications use a shared database, following the access rules defined by the main library software.


The task

Let’s imagine a client who wants to display website traffic statistics. The data is stored in a separate application or database, and the API must return it in JSON format.

Example JSON response:

{
  "error": false,
  "message": "",
  "data": {
    "Google Analytics": 150,
    "Positive Guys": 5000
  }
}

Requirements

  • Support multiple data sources and make it easy to add new ones

  • Handle different types of requests

  • Catch invalid or incorrect input data

  • Return results in JSON format

  • Do not use any framework


Solution

First, we will create the application that provides the data. In our case, it’s a PHP script returning JSON responses. The project will be split into two parts — an API application and a client.


1. Building the API application

Create a folder named api_project and inside it a file called index.php:

<?php
header("Content-Type:application/json");
if (!empty($_GET['month'])) {
    $numberOfMonth = $_GET['month'];
    $monthData = get_month($numberOfMonth);
    if (empty($monthData)) {
        response(true, "Out of Range", null);
    } else {
        response(false, "", $monthData);
    }
} else {
    response(400, "Invalid Request", null);
}

function response($status, $status_message, $data) {
    header("HTTP/1.1 " . $status);
    $response['error'] = $status;
    $response['message'] = $status_message;
    $response['data'] = $data;
    echo json_encode($response);
}

function get_month($numberOfMonth) {
    $monthlyStats = [
        "january" => ['Google Analytics' => 50, 'Positive Guys' => 500],
        "february" => ['Google Analytics' => 150, 'Positive Guys' => 5000],
    ];
    return $monthlyStats[$numberOfMonth] ?? null;
}
?>

Then create a .htaccess file in the same folder:

RewriteEngine On
RewriteRule ^([a-zA-Z_-]*)\.(html|json|xml)?$ index.php?month=$1 [NC,L]

Now the API application is accessible at:

http://localhost/api_project/?month=february

2. Building the client

Create a folder api_client and inside it a file index.php with the following content:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Monthly Website Statistics</title>
  </head>
  <body>
    <h2>Monthly Website Statistics</h2>
    <form method="POST">
      <select name="month">
        <option>Select Month</option>
        <option value="january">January</option>
        <option value="february">February</option>
      </select>
      <button type="submit" name="submit">Submit</button>
    </form>

    <h3>
    <?php
      if (isset($_POST['submit'])) {
          $name = $_POST['month'];
          $url = "http://localhost/api_project/?month=" . $name;
          $client = curl_init($url);
          curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
          $response = curl_exec($client);
          $result = json_decode($response);
          if (!empty($result)) {
              foreach ($result->data as $key => $value) {
                  echo $key . ': ' . $value . '<br>';
              }
          }
      }
    ?>
    </h3>
  </body>
</html>

You can test the application directly in your browser at:

http://localhost/api_client/

or using Postman with a request to:

localhost/api_project?month=february

Conclusion

This example does not implement best practices but provides a clear understanding of the structure and logic behind REST API in PHP.
It serves as a solid starting point for building more complex systems — including the future LibraryMS project.