简体   繁体   中英

How to add http response status to rest api in slim framework

How to add http response status to rest api in slim framework. In this code i have to fetch values through database if no data found it will show http status response

 <?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>";

      });

here i post some function to get response status and one api example to echo response... hope it helpfull.

   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++;
        }
    }

You can Just Use your response object to return json data and http status even without adding the content type header, It will be added by your response object.

    $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 
      } 
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM