【问题标题】:How to add http response status to rest api in slim framework如何在苗条框架中将http响应状态添加到rest api
【发布时间】:2018-02-16 16:30:07
【问题描述】:

如何在 slim 框架中添加 http 响应状态到 rest api。在这段代码中,如果没有找到数据,我必须通过数据库获取值,它将显示 http 状态响应

 <?php
        $app->get('/api/view', function() {
            //call connection file
            require_once('dbconnect.php');
           //array for JSON response

            $query = "select * from firm order by firmId";
            $result = $mysqli->query($query);
           // code node

            while($row = $result->fetch_assoc())
                {
                    // temp user array
                    $data[] = $row;
                }

          if (isset($data))
          {
              header('Content-Type: application/json');
           echo json_encode($data);
          }
        });
        //display single row
      $app->get('/api/view/{firmId}', function($request, $response) {
           require_once('dbconnect.php');
           $firmId = $request->getAttribute('firmId');
          $query = "select * from firm where firmId = $firmId";
          $result = $mysqli->query($query);
          $data[] = $result->fetch_assoc();

          header('Content-Type: application/json');
           echo json_encode($data)."</br>" ."</br>";

      });

【问题讨论】:

    标签: php css json html slim


    【解决方案1】:

    在这里我发布了一些函数来获取响应状态和一个 api 示例来回显响应...希望对您有所帮助。

       function verifyRequiredParams($required_fields) {
          $error = false;
          $error_fields = "";
          $request_params = array();
         $request_params = $_REQUEST;
     if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
        $app = \Slim\Slim::getInstance();
        parse_str($app->request()->getBody(), $request_params);
     }
     foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || 
     strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }
    
    if ($error) {
        $response = array();
        $app = \Slim\Slim::getInstance();
        $returncode                 =   "3";
        $returnmessage              =   'Some Fields Are Empty, Required 
       field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        $response['returncode']     =   $returncode;
        $response['returnmessage']          =   $returnmessage;
        $response['returndatacount']             =   0;
        $response['returndata']             =   array();
        echoRespnse(400, $response);
        $app->stop();
      }
    }
    
    
      function echoRespnse($status_code, $response) {
          $app = \Slim\Slim::getInstance();
          $app->status($status_code);
         $app->contentType('application/json');
        echo json_encode($response);
       }
    
      function authenticate(\Slim\Route $route) {
          $headers = apache_request_headers();
          $response = array();
          $app = \Slim\Slim::getInstance();
       if (isset($headers['BLAuth'])) {
          $db = new BLICKXDbHandler();
          $api_key = $headers['BLAuth'];
          if (!$db->isValidApiKey($api_key)) {
            $returncode                 =   "4";
            $returnmessage              =   "Authentication Fail, Wrong 
            Authorization Header Define";
            $response['returncode']             =   $returncode;
            $response['returnmessage']          =   $returnmessage;
            $response['returndatacount']             =   0;
            $response['returndata']             =   array();
            echoRespnse(200, $response);
            $app->stop();
          } else {
         }
         } else {
                $returncode  =   "4";
                $returnmessage  ="Authentication Fail, No Authorization 
           Header Define";
              $response['returncode']     =   $returncode;
               $response['returnmessage']          =   $returnmessage;
              $response['returndatacount']             =   0;
             $response['returndata']             =   array();
              echoRespnse(200, $response);
              $app->stop();
          }
        }
    
        $app->post('/getinfo', 'authenticate', function() use ($app) {
           verifyRequiredParams(array('usertype'));
           $usertype       =   $app->request()->post('usertype');
           $response       =   array();
         $db = new BLICKXDbHandler();
        $result         =   array();
        if(isset($usertype) && $usertype=="fr")
        {
           $result = $db->getFranchisedetails();
        }
        else if(isset($usertype) && $usertype=="op")
        {
         $result = $db->getOperatordetails();
       }
         if(count($result)==0)
         {
          $returncode                 =   "1";
          $returnmessage              =   "No Data Found";
          $response['returncode']     =   $returncode;
          $response['returnmessage']          =   $returnmessage;
          $response['returndatacount']             =   0;
          $response['returndata']             =   array();
      }
      else
      {
    
          $response           =   array();
          $returncode         =   "0";
          $returnmessage      =   "Data Listed Sucessfully";
    
          $alldata = array();
          $kk=0;
          if(isset($usertype) && $usertype=="fr")
           {
              foreach ($result as $key => $task) {
                $franchise_id           =   $task["franchise_id"];
                $franchise_name         =   $task["franchise_name"];
                $alldata[$kk]['id']     =   $franchise_id;
                $alldata[$kk]['name']   =   $franchise_name;
                $kk++;
            }
        }
    

    【讨论】:

      【解决方案2】:

      您可以只使用您的响应对象来返回 json 数据和 http 状态 即使不添加内容类型标头,它也会由您的响应对象添加。

          $app->get('/api/view', function() {
              //call connection file
              require_once('dbconnect.php');
             //array for JSON response
      
              $query = "select * from firm order by firmId";
              $result = $mysqli->query($query);
             // code node
      
              while($row = $result->fetch_assoc())
                  {
                      // temp user array
                      $data[] = $row;
                  }
      
            if (isset($data))
            {
                //header('Content-Type: application/json');
                //echo json_encode($data);
                //send json data wih http status 
                return $response->withJson($data,200);
                //Where 200 is the http status
            }
           else{
                  $message=array("message"=>"empty data")
                  return $response->withJson($message,404);
                  //Where 404 is not found  http status for example 
            } 
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 2018-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 2015-05-02
        相关资源
        最近更新 更多