<?php
/**
* Function to make an API request with metadata and retry logic.
*
* @param string $url The URL to make the request to.
* @param array $headers Optional array of HTTP headers.
* @param array $metadata Optional array of metadata to attach to the response.
* @param int $maxRetries Maximum number of retries.
* @param int $retryDelay Delay between retries in seconds.
* @return mixed|null The response body if successful, null on failure.
*/
function apiRequestWithMetadataAndRetry(string $url, array $headers = [], array $metadata = [], int $maxRetries = 3, int $retryDelay = 2): ?mixed
{
$retries = 0;
while ($retries < $maxRetries) {
try {
// Make the API request
$response = file_get_contents($url, false, $headers);
if ($response === false) {
throw new Exception("Failed to fetch URL: " . $url);
}
// Attach metadata to the response
$response = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Failed to decode JSON: " . json_last_error_msg());
}
$response['metadata'] = $metadata;
return $response; // Return the response if successful
} catch (Exception $e) {
$retries++;
if ($retries >= $maxRetries) {
error_log("API Request failed after " . $maxRetries . " retries: " . $e->getMessage());
return null; // Return null if max retries reached
}
// Wait before retrying
sleep($retryDelay);
}
}
return null; // Should not reach here, but added for safety.
}
//Example Usage:
/*
$url = 'https://api.example.com/data';
$headers = ['Content-Type: application/json'];
$metadata = ['timestamp' => time(), 'user_id' => 123];
$response = apiRequestWithMetadataAndRetry($url, $headers, $metadata, 5, 5);
if ($response) {
echo "<pre>";
print_r($response);
echo "</pre>";
} else {
echo "API request failed.";
}
*/
?>
Add your comment