Search code examples
phprestapihttprequestpathinfo

Rest API: What do first, distinguish REQUEST_METHOD or PATH_INFO?


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 possibleREQUEST_METHOD`.


Solution

  • 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();
    }