Integrating an Exchange Rate API in PHP
August 13, 20263 min readCurrencyRest

Integrating an Exchange Rate API in PHP

Tutorialsexchange rate apiphplaravel

Integrating an Exchange Rate API in PHP (Laravel-Friendly)

When developing applications that require currency conversion, integrating an exchange rate API can streamline the process significantly. If you’re a PHP developer, particularly using Laravel, you’ll find that leveraging a robust API like CurrencyRest simplifies fetching and utilizing both real-time and historical exchange rates for over 200 currencies, including 108 fiat and 94 cryptocurrencies.

Getting Started with CurrencyRest

Before diving into the code, you need to create a free account at CurrencyRest. With this account, you’re granted up to 300 requests per month at no cost, giving you full access to every currency pair.

Making API Requests

To access exchange rates, you’ll be making a simple HTTP GET request. Below is a typical example of how you might convert 100 USD to XOF (West African Franc) using CurrencyRest:

$response = file_get_contents('https://api.currencyrest.com/api/v1/convert?from=USD&to=XOF&amount=100');
$data = json_decode($response, true);
$convertedAmount = $data['result']['conversion_result'];

In the code snippet above:

  • We use file_get_contents() to send a GET request to the CurrencyRest API.
  • We then decode the JSON response into a PHP associative array with json_decode().
  • Finally, we extract the converted amount from the response.

Caching Responses

To optimize performance and reduce the number of requests made to the API, consider implementing caching. You can use Laravel's built-in caching mechanisms, which can greatly enhance the efficiency of your application. Here’s a quick example:

use IlluminateSupportFacadesCache;

function getExchangeRate($from, $to, $amount) {
    $cacheKey = "currency_{$from}_{$to}";
    return Cache::remember($cacheKey, 60, function () use ($from, $to, $amount) {
        $response = file_get_contents("https://api.currencyrest.com/api/v1/convert?from={$from}&to={$to}&amount={$amount}");
        return json_decode($response, true);
    });
}

In this example:

  • We define a function getExchangeRate() that accepts parameters for the currencies and amount.
  • We create a unique cache key based on the currency pair.
  • We cache the result for 60 minutes, reducing unnecessary calls to the API.

Formatting Response Data

When working with currency data, it's essential to format the output for user display. You may want to round off the converted amount or even format it as a currency string. Here’s how you can do that:

$formattedAmount = number_format($convertedAmount, 2, '.', ',');
echo "100 USD is approximately {$formattedAmount} XOF";

This will give you a neatly formatted output for better readability.

Handling Errors

Error handling is crucial when integrating any external API. Be sure to check for potential errors in the response. Here’s how you might modify your API request logic to handle errors gracefully:

try {
    $response = file_get_contents('https://api.currencyrest.com/api/v1/convert?from=USD&to=XOF&amount=100');
    $data = json_decode($response, true);
    if (isset($data['error'])) {
        throw new Exception($data['error']['message']);
    }
    $convertedAmount = $data['result']['conversion_result'];
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Conclusion

Integrating the CurrencyRest exchange rate API into your PHP applications is not only straightforward but also robust for handling real-time currency conversion. With the ability to cache responses and format output, your application can provide users with a seamless currency conversion experience.

Don't miss out on trying CurrencyRest for free—sign up today and enjoy 300 requests per month with full access to all currency pairs!

Call to Action

Start integrating exchange rate data into your applications today! Sign up for free here.


CurrencyRest

Author