I am working on a small REST API
, written in PHP
.
Is there a best practice, to decide what the script should do?
Do I first check if the request is GET
, POST
, PUT
, DELETE
or do I check first the PATH_INFO
.
Example first check PATH_INFO
:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($request)
{
case 'books':
if ($method = 'GET')
{
getbooks();
} elseif ($method = 'POST')
{
postbooks();
}
break;
default:
include_once('error.php');
break;
}
Example first check REQUEST_METHOD:
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
switch ($method)
{
case 'GET':
if ($request = 'books')
{
getbooks();
} elseif ($request = 'user')
{
getuser();
}
break;
default:
include_once('error.php');
break;
}
Thank you in advance!
Also, the APIwill be very limited. Mostly a path will have only one possible
REQUEST_METHOD`.
If you want to keep it simple and understandable. Then I would prefer the following
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'))[0];
if($method == "GET" && $request == "books"){
getBooks();
}elseif ($method == "POST" && $request == "books"){
addBooks();
}elseif ($method == "PUT" && $request == "books"){
updateBooks();
}elseif ($method == "DELETE" && $request == "books"){
deleteBooks();
}