Back

ThirdPartyAPIHandler

Copy Below Code View As A Text File Show Text Only Show API Edit Code
                            

class ThirdPartyAPIHandler { private $apiKey; public function __construct($apiKey) { $this->apiKey = $apiKey; } public function makeAPIRequest($url, $method = 'GET', $data = array()) { $curl = curl_init(); $headers = array( 'Authorization: Bearer ' . $this->apiKey, 'Content-Type: application/json' ); $options = array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers ); if ($method === 'POST' || $method === 'PUT') { $options[CURLOPT_POSTFIELDS] = json_encode($data); } curl_setopt_array($curl, $options); $response = curl_exec($curl); $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); if ($response === false) { throw new Exception('API request failed: ' . curl_error($curl)); } $responseData = json_decode($response, true); if ($httpCode !== 200) { throw new Exception('API responded with status code ' . $httpCode . ': ' . $responseData['message']); } return $responseData; } } // Example usage $apiKey = 'your_api_key_here'; $apiHandler = new ThirdPartyAPIHandler($apiKey); $url = 'https://api.example.com/resource'; $response = $apiHandler->makeAPIRequest($url); print_r($response);