Home > Software design >  api rest on CI 3
api rest on CI 3

Time:04-05

I am unable to get working API rest to check a license health.

api.php (under controller)

<?php
   
   require APPPATH . '/libraries/REST_Controller.php';
   use Restserver\Libraries\REST_Controller;
     
class Inmobiapi extends REST_Controller {
    
      /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function __construct() {
       parent::__construct();
       $this->load->database();
    }
       
    /**
     * Get All Data from this method.
     *
     * @return Response
    */
    public function index_post()
    {
        $licencia=$this->input->post('licencia');
        if($licencia){
            $data = $this->db->get_where("clientes", ['licencia' => $licencia,'status'=>'Active'])->row_array();
        }else{
            $this->response(NULL, 404);
        }
     
        $this->response($data, REST_Controller::HTTP_OK);
    }      
        
}

function to check a license, it's a helper.

function verificar_licencia($licencia){
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, 'URL_TO_API');
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $licencia);
                
    $buffer = curl_exec($curl_handle);
    curl_close($curl_handle);
    
    $result = json_decode($buffer);

    if(isset($result))
    {
        return $result;
    }
    
    else
    {
        return FALSE;
    }
}

The return always give me FALSE. The api file is hosted on other domain with different CI3 installation but same configuration on both rest.php

Auth is not enabled so, anybody can access (I am just testing).

Can somebody guide me? Thanks.

CodePudding user response:

I am assuming that you have a value for 'URL_TO_API' that is valid. Check your CURL options. If you're not getting a result from the call and your URL is valid and functional, your curl_setopt calls may have missing or incorrect properties being set (or not set).

For example, in my latest project, my curl options had to be set as follows:

    curl_setopt_array($curl, [
        CURLOPT_URL => 'https://path/to/endpoint'
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_VERBOSE => 1,
        CURLOPT_NOBODY => 1,
        CURLOPT_MAXREDIRS => 1,
        CURLOPT_POST => 1,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_HTTPHEADER => []
    ]);

It may be different for you, depending on:

  • What you want to achieve with the call.
  • What the endpoint requires you to set - refer to your endpoint documentation.
  • Related