
Learn best practices for integrating external APIs using PHP and cURL with proper error handling.
Integrating third-party APIs is a common requirement in modern web applications. Let's explore how to do this effectively using PHP and cURL.
function makeApiRequest($url, $method = 'GET', $data = null) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); if ($data) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen(json_encode($data)) ]); } $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return [ 'code' => $httpCode, 'data' => json_decode($response, true) ]; }
try { $result = makeApiRequest('https://api.example.com/data'); if ($result['code'] !== 200) { throw new Exception('API request failed: ' . $result['code']); } // Process successful response return $result['data']; } catch (Exception $e) { Log::error('API Integration Error: ' . $e->getMessage()); return null; }
Proper API integration requires attention to error handling, security, and performance. Following these patterns will help you build reliable integrations.
Published on March 10, 2024