Answer the question
In order to leave comments, you need to log in
How to make your own REST API?
Hello, you need to make your own API service in PHP, which will have REST-style data access functionality. Using a database.
What would work like this:
GET /api/games/ - list of toys
GET /api/game/12345/ - information about the toy
POST /api/games/ + JSON - add a new toy
PUT /api/games/12345/ + JSON - update an existing toy
DELETE /api/games/12345/ - delete a toy
The data is returned in JSON, using as many HTTP statuses as possible. You can use ready-made solutions via composer.
How to do what I described above, I can only receive JSON using ajax, but how to do my own, I have no idea from the word at all. It is desirable to have some simple example with explanations or a link where it is all simply explained, again with examples where everything is as clear and simple as possible, or using your example. newbie in this business.
Answer the question
In order to leave comments, you need to log in
index.php
<?php
# Author - Fedor Vlasenko, [email protected]
define('METHOD', $_SERVER['REQUEST_METHOD']);
define('URI', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
function router($url, ...$args)
{
(empty($args[1]) || false !== strpos(METHOD, $args[0]))
&& (URI === $url || preg_match('#^' . $url . '$#iu', URI, $match))
&& die(call_user_func_array(end($args), $match ?? []));
}
router('/api/games', 'GET', function () {
echo 'список игрушек';
});
router('/api/game/(\d+)', 'GET', function (...$args) {
echo 'информация о игрушке: ', $args[1];
});
router('/api/games', 'POST', function () {
echo 'добавить новую игрушку';
});
router('/api/games/(\d+)', 'PUT', function (...$args) {
echo 'обновить существующую игрушку: ', $args[1];
});
router('/api/games/(\d+)', 'DELETE', function (...$args) {
echo ' удалить игрушку: ', $args[1];
});
header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
echo '404';
The easiest way to start is to auto-generate code according to the OpenAPI specification (swagger).
Specification editor online: https://editor.swagger.io/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question