Skip to content

Instantly share code, notes, and snippets.

@cyberdev
Created February 2, 2021 04:25
Show Gist options
  • Save cyberdev/45d59b1d5ef057e802a7845d0625b731 to your computer and use it in GitHub Desktop.
Save cyberdev/45d59b1d5ef057e802a7845d0625b731 to your computer and use it in GitHub Desktop.
CURL method to consume REST API
private function request($endpoint, $method='GET', $body=false) {
$url = "https://example.com$endpoint";
$token = 'API_TOKEN';
$headers = [
"Authorization: Token token=$token",
"Content-Type: application/json";
];
if($body!==false){
if($method=='GET'){
$url .= '?' . http_build_query($body);
}
}
// Send request to Server
$curl = curl_init($url);
if($body!==false && $method!=='GET'){
$body = json_encode($body);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
}
// To save response in a variable from server, set headers;
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
// Get response
if(!($curl_response = curl_exec($curl))){
$return = [
'message' => curl_error($curl)
];
}else{
$return = json_decode($curl_response, true);
}
curl_close($curl);
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment