Skip to content

Instantly share code, notes, and snippets.

@gregmercer
Last active December 22, 2015 11:19
Show Gist options
  • Save gregmercer/6465114 to your computer and use it in GitHub Desktop.
Save gregmercer/6465114 to your computer and use it in GitHub Desktop.
Helper function for making REST calls using php.
/***********************************************************
helper function for rest api
for more info on how to use this function... see:
https://gist.github.com/gregmercer/6465411
***********************************************************/
function rest_helper($url, $params = null, $verb = 'GET', $format = 'json', $authorization = null) {
// setup auth header
$cparams = array(
'http' => array(
'method' => $verb,
'ignore_errors' => true
)
);
if ($authorization != null) {
$cparams['http']['header'] = "Authorization: $authorization";
}
// setup query params
if ($params !== null) {
$params = http_build_query($params);
if ($verb == 'POST') {
$cparams['http']['content'] = $params;
} else {
$url .= '?' . $params;
}
}
// create context - combining header and params
$context = stream_context_create($cparams);
// make call to url
$fp = fopen($url, 'rb', false, $context);
if (!$fp) {
$res = false;
} else {
$res = stream_get_contents($fp);
}
if ($res === false) {
throw new Exception("$verb $url failed: $php_errormsg");
}
switch ($format) {
case 'json':
$r = json_decode($res);
if ($r === null) {
throw new Exception("failed to decode $res as json");
}
return $r;
case 'xml':
$r = simplexml_load_string($res);
if ($r === null) {
throw new Exception("failed to decode $res as xml");
}
return $r;
}
// return response
return $res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment