Welcome Guest, Not a member yet? Register   Sign In
Consuming JSON API
#1

What is the best way to consume remote API's in codeignitor and should the call go in the model or the controller?
Reply
#2

this is one way to do it. so in the controller

PHP Code:
function getItemsFor($orderid){

 if( ! 
$items $this->awesomeorders->returnItems($orderid) )
 
 {
 
    $this->_showNoItemsForOrder($orderid) ; 

 
 
 
 else{

 
     $this->_showApiOrderItems($items) ; 

 
      



in the model awesomeorders

PHP Code:
function returnItems($orderid){

     
 // set HTTP header
$headers = array('Content-Type: application/json',);

// the url of the API you are contacting to 'consume' 
$url 'https://someservice.com/jsonOrderItems/'.$orderid 

// Open connection
$ch curl_init();

// Set the url, number of GET vars, GET data
curl_setopt($chCURLOPT_URL$url);
curl_setopt($chCURLOPT_POSTfalse);
curl_setopt($chCURLOPT_HTTPHEADER$headers);
curl_setopt($chCURLOPT_RETURNTRANSFERtrue );

curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);

// Execute request
$result curl_exec($ch);

// Close connection
curl_close($ch);

// get the result and parse to JSON
$items json_decode($result);

 
  if(isset($items)){ return $items ; }

 
  else { return FALSE ; }


}
// 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB