CodeIgniter Forums
Consuming JSON API - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Consuming JSON API (/showthread.php?tid=64261)



Consuming JSON API - dadonk - 02-01-2016

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


RE: Consuming JSON API - cartalot - 02-01-2016

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


}
//