API with Authorization in PHP
It is possible to make an API not public, but private, accessible only with a password. In this case, when accessing our API, in each request, besides the parameters, the correct password will need to be passed. Such a password is called a token.
Users of our API will have to obtain this token somehow. For example, by purchasing it. In this case, each purchaser will have their own token.
Let's look at working with tokens with an example. Let our API accept a number as a parameter and return the square of that number. Let's make this API private. Let's proceed with the implementation.
To start, for simplicity, let's make one common token and store it in plain text in a file:
<?php
$token = '12345';
?>
This is how we will access our API, passing the parameter and the token:
http://api.loc/index.php?num=100&token=12345
Let's implement the API with token verification:
<?php
$token = '12345';
if (isset($_GET['token']) and $_GET['token'] === $token) {
if (isset($_GET['num'])) {
echo $_GET['num'] ** 2;
} else {
echo 'error';
}
} else {
echo 'incorrect token';
}
?>
Create an API that will accept a birth date as a parameter and return how many days are left until that date. Implement token-based authorization.
Modify the previous task so that both the parameter and the token are passed using the POST method.
Modify the previous task so
that the token is passed through the HTTP
header X-Token.
Make it so that tokens are stored in a database and each API user has their own token.
Limit the number of API requests
for each user to 10
per day.