Skip to content

Instantly share code, notes, and snippets.

@varunity
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varunity/bc041214007fe825c467 to your computer and use it in GitHub Desktop.
Save varunity/bc041214007fe825c467 to your computer and use it in GitHub Desktop.
PHP script to call HarvestAPI
<?php
// modified code from https://stackoverflow.com/questions/9802788/call-a-rest-api-in-php
// Method: POST, PUT, GET etc
// Data: array("param" => "value") ==> index.php?param=value
/*
//had to install php curl
sudo apt-get install php5-curl
sudo service apache2 restart
//It's possible you'll need to install more:
sudo apt-get install curl libcurl3 libcurl3-dev;
*/
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
// use function on root level of API to show all available API endpoints
$endpoints = CallAPI('GET', 'harvestdata.herokuapp.com');
print_r($endpoints);
//call farmers resource to return string
$farmers = CallAPI('GET', 'harvestdata.herokuapp.com/farmers/');
//convert JSON string to PHP variable (object)
$farmer_objects = json_decode($farmers);
$num_farmers = $farmer_objects->count;
$next_page_url = $farmer_objects->next;
echo "the next 10 results of ".$num_farmers." are found here:".$next_page_url;
//now get the actual farmers from results
$fama_dem = $farmer_objects->results;
foreach ($fama_dem as $fama) {
// code...
echo '<p>Farmer :</p>';
echo nl2br($fama->first_name." ".$fama->last_name);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment