PHP REST API and CLIENT

I’m trying to implement a RESTful API for my web app.
I have learned from some tutorials how to write the classes for REST API service.

However, in one of the tutorials, they use AngularJS to send HTTP.delete requests to the server on button clicks.
If I don’t want to use AngularJS, how can I set the request method in the HTML form to delete a specified user?

For example, if I go to localhost/app/api/user/3
I will get the information of User of id 3 in JSON representation because the default request method is GET.

How can I send delete request to localhost/app/api/user/3 and to delete this user?

In HTML forms, there are only POST and GET methods.

I also don’t know how the PUT works…

The following are the classes:

<?php
class REST {
  public $_request_args = array();
  private $_method = "";
  public $_content_type = "application/json";
  private $_code = 200;

  public function __construct() {
      $this->inputs();
  }

  private function inputs() {
    $this->_method = $this->get_request_method();
    switch($this->_method){
        case "POST":
            $this->_request_args = $this->cleanInputs($_POST);
            break;
        case "GET":
            $this->_request_args = $this->cleanInputs($_GET);
            break;
        case "DELETE":
        case "PUT":
            parse_str(file_get_contents("php://input"),$this->_request_args);
            $this->_request_args = $this->cleanInputs($this->_request_args);
            break;
        default:
            $this->response('Method Not Allowed',405);
            break;
      }
  }

  private function get_status_message(){
      $status = array(
        200 => 'OK', 
        204 => 'No Content',  
        404 => 'Not Found',  
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        500 => 'Internal Server Error');
      return ($status[$this->_code]) ? $status[$this->_code] : $status[500];
  }

  public function get_request_method(){
      $request_method = $_SERVER['REQUEST_METHOD'];
      if ($request_method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
          if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
            $request_method = 'DELETE';
          } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
            $request_method = 'PUT';
          } else {
            throw new Exception("Unexpected Header");
          }
      }
      return $request_method;
  }

  private function cleanInputs($data){
      $clean_input = array();
      if (is_array($data)) {
         foreach ($data as $k => $v) {
            $clean_input[$k] = $this->cleanInputs($v);
         }
      } else {
         if(get_magic_quotes_gpc()) {
            $data = trim(stripslashes($data));
         }
         $data = strip_tags($data);
         $clean_input = trim($data);
      }
      return $clean_input;
   }        

   private function set_headers() {
      header("HTTP/1.1 ".$this->_code." ".$this->get_status_message());
      header("Content-Type:".$this->_content_type);
   }

   public function response($data, $status = 200) {
       $this->_code = ($status)? $status : 200;
       $this->set_headers();
       if (is_array($data))
          echo json_encode($data, JSON_PRETTY_PRINT);
       else
          echo $data;
       exit;
    }
}   
?>


<?php
class API extends REST {
public $data = "";
public function processApi() {
    $request_args = explode('/', rtrim($_SERVER["REQUEST_URI"], '/'));
    $func = $request_args[3];
    if(method_exists($this, $func))
        $this->$func();
    else {
        $this->response('',404); // If the method not exist with in this class "Page not found".
     }
  }

  private function users() {
    if($this->get_request_method() != "GET"){
        $this->response('',405);
    }
    $conn = DBManager::getConnection();
    $stmt = $conn->prepare("SELECT * FROM USER");
    $stmt->execute();
    $result = $stmt->fetchAll();
    $this->response($result);
  }

  private function courses() {
    if($this->get_request_method() != "GET"){
        $this->response('',405);
    }
    $conn = DBManager::getConnection();
      $stmt = $conn->prepare("SELECT * FROM COURSE");
      $stmt->execute();
      $result = $stmt->fetchAll();
      $this->response($result);
   }

   private function subjects() {
       if($this->get_request_method() != "GET"){
          $this->response('',405);
       }
       $conn = DBManager::getConnection();
       $stmt = $conn->prepare("SELECT * FROM SUBJECT");
       $stmt->execute();
       $result = $stmt->fetchAll();
       $this->response($result);
   }
}

$api = new API;
$api->processApi();
?>

So my question is if I have a form like the following:

<form action='api/users/3' method='POST'>
    <input type='submit' value='Delete User' />
</form>

How can I actually delete this user with that request even though the method is POST not DELETE?
Thanks in advance.

You are correct you will use the forms POST method and pass the user id through the request. You will probably need a hidden input that contains the user id to be passed in the post. Or you can use javascript and build a custom post request.

<form action='api/users/3' method='POST'>
    <input type='hidden' name = "user_id" value=<?php echo "$user_id"; ?> />
    <input type='submit' name = "submit" value='Delete User' />
</form>

I tried as you said, but I haven’t seen HTTP_X_HTTP_METHOD in $_SERVER array?

use the $_POST global array! it should contain the current POST request.

I dont need to see hidden value in a $_POST array. I would like to see $_SERVER['HTTP_X_HTTP_METHOD']

$_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
            $request_method = 'PUT';
          }

Html only supports GET and POST requests. If you want to use a PUT you will need to build a custom HTTP request using javascript or cURL library. But a PUT method is not advisable and makes no sense to use on a request just passing data. PUT is used for resources and files and not a good solution to use to pass data over an http request. Using a POST request is the best option. I would also advise on looking up the differences and reason for each request type. Mainly GET, POST and PUT and what they are used for.

Ok. Then please help to build custom HTTP request using javascript or cURL in my simple form. So my aim is to understand PUT.

This is using jquery to sent the request

$.ajax({
   url: '/api/users/3',
   type: 'PUT',
  contentType:"text/plain",
   success: function(response) {
         // do something with the response
   }
});
1 Like

but how it would in pure Javascript?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.