Integrating Exchange Rate API in PHP
Introduction
Integrating an exchange rate API in PHP, particularly within a Laravel framework, can streamline the process of accessing real-time and historical currency rates. CurrencyRest provides an excellent REST API that aggregates information from various sources, ensuring accuracy and reliability.
Why Choose CurrencyRest?
CurrencyRest offers an abundance of benefits:
- Wide Coverage: Supports over 180 fiat currencies and nearly 100 cryptocurrencies.
- Data Aggregation: Combines data from central banks, markets, and exchanges to enhance reliability.
- Flexible Plans: Start with a free tier of 300 requests/month which scales to business plans for higher needs.
Setting Up Your PHP Environment
Before diving into the API integration, ensure that your PHP environment is set up. You'll want to have Composer for dependencies and Laravel installed. To create a new Laravel project:
composer create-project --prefer-dist laravel/laravel currencyApp
Making API Calls with CurrencyRest
CurrencyRest provides easy access to exchange rates through simple HTTP requests. Here's a typical API call to convert currencies:
$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']['amount'];
This code fetches the exchange rate for converting 100 USD to XOF (West African Franc).
Caching the Data
To reduce the number of API calls and improve performance, implementing caching is essential. Laravel provides a robust caching system. Here’s how you can cache the results:
use Illuminate\Supportacades\Cache;
// Check if we have the cached result
$cacheKey = 'exchange_rate_usd_xof';
$exchangeRate = Cache::remember($cacheKey, 60, function () {
$response = file_get_contents('https://api.currencyrest.com/api/v1/convert?from=USD&to=XOF&amount=100');
return json_decode($response, true);
});
The above snippet caches the exchange rate for 60 minutes, minimizing redundant API calls.
Formatting the Response
Once you have the data, formatting it appropriately is crucial. Here’s a basic way to display the formatted result:
echo "Converted Amount: $convertedAmount XOF";
Conclusion
By integrating the CurrencyRest API into your PHP application, you can efficiently work with exchange rates while leveraging Laravel’s powerful tools for caching and data management.
Don’t forget to test extensively and account for error handling, especially in production applications.
Call to Action
Ready to get started? Sign up at CurrencyRest today and enjoy 300 free requests per month!
CurrencyRest
Author