Created
February 2, 2021 04:25
-
-
Save cyberdev/45d59b1d5ef057e802a7845d0625b731 to your computer and use it in GitHub Desktop.
CURL method to consume REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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