REST API in PHP

There are special approaches that standardize APIs for the common convenience of both API developers and its users.

One such approach is REST API. It is based on the idea that for CRUD operations it is necessary to use different methods of the HTTP protocol.

To retrieve data - the GET method, to create data - the POST method, to modify data - the PUT method, to delete data - the DELETE method.

As an example, let's consider some API that manipulates users. Let's see what the URLs will look like for different actions.

Get all users:

urlGET http://api.loc/users/

Get one user by their id:

urlGET http://api.loc/user/1/

Create a user:

urlPOST http://api.loc/user/

Modify a user by their id:

urlPUT http://api.loc/user/1/

Delete a user by their id:

urlDELETE http://api.loc/user/1/

Let's see how REST API is implemented in PHP. There is a certain problem here. The fact is that both PHP and CURL support only GET and POST methods:

api.loc/index.php<?php
  $method = $_SERVER['REQUEST_METHOD'];
  var_dump($method); // only GET and POST
?>

Therefore, to implement REST API, we will have to resort to a trick. Its essence is that in reality, data will be transmitted only by GET and POST methods, but we will simulate the work of other methods using a custom HTTP header. Let's call it, for example, HTTP-X-HTTP-METHOD.

Then we can get the contents of this header as follows:

api.loc/index.php<?php
  $method = $_SERVER['HTTP-X-HTTP-METHOD'];
?>

Now we can write the API implementation:

api.loc/index.php<?php
  $method = $_SERVER['HTTP-X-HTTP-METHOD'];
  
  switch ($method)  {
    case 'GET':
      // ...
    break;
    case 'POST':
      // ...
    break;
    case 'PUT':
      // ...
    break;
    case 'DELETE':
      // ...
    break;
  }
?>
Задание 1

Implement a REST API for products of an online store.

Задание 2

Test the implemented API using the CURL library.