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:
GET http://api.loc/users/
Get one user by their id:
GET http://api.loc/user/1/
Create a user:
POST http://api.loc/user/
Modify a user by their id:
PUT http://api.loc/user/1/
Delete a user by their id:
DELETE 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:
<?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:
<?php
$method = $_SERVER['HTTP-X-HTTP-METHOD'];
?>
Now we can write the API implementation:
<?php
$method = $_SERVER['HTTP-X-HTTP-METHOD'];
switch ($method) {
case 'GET':
// ...
break;
case 'POST':
// ...
break;
case 'PUT':
// ...
break;
case 'DELETE':
// ...
break;
}
?>
Implement a REST API for products of an online store.
Test the implemented API using the CURL library.