簡體   English   中英

設置REST API的請求方法

[英]Set Request Methods for REST API

我正在嘗試為我的Web應用程序實現RESTful API。
我從一些教程中學到了如何為REST API服務編寫類。

但是,在其中一本教程中,他們使用AngularJS在單擊按鈕時將HTTP.delete請求發送到服務器。
如果我不想使用AngularJS,如何在HTML表單中設置請求方法以刪除指定的用戶?

例如,如果我轉到localhost/app/api/user/3
我將以JSON表示形式獲取ID為3的用戶的信息,因為默認的請求方法是GET

如何將刪除請求發送到localhost/app/api/user/3並刪除該用戶?

在HTML表單中,只有POST和GET方法。

我也不知道PUT是如何工作的...

以下是類:

<?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["PATH_INFO"], '/'));
    $func = array_shift($request_args);
    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();
?>

所以我的問題是我是否有如下表格:

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

即使方法是POST not DELETE ,我如何實際通過該請求刪除該用戶?

我檢查了其他帖子,但這個問題沒有答案!

瀏覽器不支持HTTP DELETE和PUT在HTML表單的方法。 要獲取DELETE方法的支持,您可以將您的形成假性“方法”(一個隱藏的文本元素),這是多么苗條微風路由器/“微架構”手柄PUT和DELETE方法。

<form action='api/users/3' method='POST'>
    <input type="hidden" name="_method" value="PUT | DELETE" />
    <input type='submit' value='Delete User' />
</form>

在Breeze中,在PHP腳本中使用DELETE方法將如下所示:

delete('/', function(){
    echo 'you made a DELETE request';
});

您也許可以做類似的事情。 或者,您可以考慮切換到支持DELETE和PUT的REST路由器或微框架。

對於Google Chrome,您可以安裝一個非常有用的擴展程序,該擴展程序可以幫助您開發和測試REST API: Advanced REST Client

另外,您需要指定HTTP.delete大小寫,如下所示:

case "DELETE":
    parse_str(file_get_contents("php://input"),$this->_request_args);
    $this->_request_args = $this->cleanInputs($this->_request_args);
    break;

processApi()函數似乎存在問題,因為這不是您獲取參數的方式。

修復您的HTACCESS文件以正確重定向URL。

請遵循本教程以獲取更多信息: http : //coreymaynard.com/blog/creating-a-restful-api-with-php/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM