1. <?php
  2. /**
  3. * Function to make an API request with metadata and retry logic.
  4. *
  5. * @param string $url The URL to make the request to.
  6. * @param array $headers Optional array of HTTP headers.
  7. * @param array $metadata Optional array of metadata to attach to the response.
  8. * @param int $maxRetries Maximum number of retries.
  9. * @param int $retryDelay Delay between retries in seconds.
  10. * @return mixed|null The response body if successful, null on failure.
  11. */
  12. function apiRequestWithMetadataAndRetry(string $url, array $headers = [], array $metadata = [], int $maxRetries = 3, int $retryDelay = 2): ?mixed
  13. {
  14. $retries = 0;
  15. while ($retries < $maxRetries) {
  16. try {
  17. // Make the API request
  18. $response = file_get_contents($url, false, $headers);
  19. if ($response === false) {
  20. throw new Exception("Failed to fetch URL: " . $url);
  21. }
  22. // Attach metadata to the response
  23. $response = json_decode($response, true);
  24. if (json_last_error() !== JSON_ERROR_NONE) {
  25. throw new Exception("Failed to decode JSON: " . json_last_error_msg());
  26. }
  27. $response['metadata'] = $metadata;
  28. return $response; // Return the response if successful
  29. } catch (Exception $e) {
  30. $retries++;
  31. if ($retries >= $maxRetries) {
  32. error_log("API Request failed after " . $maxRetries . " retries: " . $e->getMessage());
  33. return null; // Return null if max retries reached
  34. }
  35. // Wait before retrying
  36. sleep($retryDelay);
  37. }
  38. }
  39. return null; // Should not reach here, but added for safety.
  40. }
  41. //Example Usage:
  42. /*
  43. $url = 'https://api.example.com/data';
  44. $headers = ['Content-Type: application/json'];
  45. $metadata = ['timestamp' => time(), 'user_id' => 123];
  46. $response = apiRequestWithMetadataAndRetry($url, $headers, $metadata, 5, 5);
  47. if ($response) {
  48. echo "<pre>";
  49. print_r($response);
  50. echo "</pre>";
  51. } else {
  52. echo "API request failed.";
  53. }
  54. */
  55. ?>

Add your comment