Back to all courses
In this video we review what RapidAPI is & how you can use it to connect & integrate multiple APIs into your Laravel application with a single API key. We are going to integrate with a currency conversion API & build a flexible API wrapper that we can use to connect to multiple APIs that are on RapidAPI.
I've been coding since 2005 & my very first website was built with HTML, CSS, & PHP all in a single index.php file (good old times). I decided to make my own channel and start producing content on things that I know & have learned over the years as well as the things that I will learn along the way. Currently, my main stack consists of PHP, Laravel, GraphQL, React JS (Next.js & Gatsby) & Tailwind CSS. (Though, I am planning on exploring others soon like Flutter & Dart)
Building applications sometimes feels cumbersome because it often involves using third-party APIs, whether you're working with a single API or multiple ones. Digging and playing around with the API’s documentation, testing it out, and making it work for your application requires a lot of time. How to solve this problem? This guide is going to explain this in an exciting way.
Each API has its API key, which requires a different process and brings more integration complexity. Not all API documentation is as good as Laravel documentation. This is where RapidAPI comes in and solves all your problems. Through RapidAPI, we can integrate and manage multiple APIs from a single platform using a single API key and SDK.
Before discussing our topic, let’s highlight a slight discourse on RapidAPI. What exactly is RapidAPI?
RapidAPI is the world's largest API Hub. You can think of RapidAPI as a GitHub for APIs, a next-generation platform where developers discover and connect to thousands of APIs. Using RapidAPI, developers can search and test the APIs, subscribe, and link to the APIs.
When you search for any API on RapidAPI, you will notice three identifiers in each API card, i.e., popularity, average latency, and service level. These identifier assists in decision-making and preferred choice for selecting any API. If you don’t know what they mean, let me explain it to you.
Popularity explains how popular a particular API is on RapidAPI. It's an internal score; hence, the higher the number you see, the more popular it is. For example, the following picture shows different weather APIs. Among them, ‘Open Weather Map’ is the most popular with a popularity score of 9.9, followed by ‘Forecast’ at 9.8 and ‘OpenWeather’ at 9.1.
Average latency is the average response time from the API in milliseconds. The lesser the response times or average latency, the better is client satisfaction, lesser costs, and higher customer satisfaction.
Service level means a percentage of successful API calls. It describes the acceptable level of service availability and performance to a customer, provider, or both.
This guide will integrate the Laravel application with a currency converter API. I've already set up the basic Laravel project with the basic UI using the TailwindCSS so that we can just focus on building the backend part to integrate with RapidAPI.
Before we go any further, let’s quickly talk about Laravel. It is an open-source web MVC framework for PHP. Its robust framework provides an easy formulation of PHP web applications, such as a modular packaging system with a dedicated dependency manager, access to relational databases, and other utilities for application deployment and maintenance.
Let's set up a Laravel project with the basic UI using the TailwindCSS. This will help us focus on building the backend part of it and integrating it with RapidAPI.
We can start by taking an example of the basic UI of currency conversion. We all know about its working mechanism. We can simply put any currency value, click the convert, and it gives us a hard-coded value.
We are going to sync it with API. The reason is that when we click convert, we want the information to come from the API we aim to integrate instead of getting a hard-coded value. Let's do it in simple steps:
First of all, we need to know how this hard-coded value appears. This is, in fact, a controller method that gets the code when we click convert. Before moving further, let's see the code here:
php
<?phpnamespace App\Http\Controllers;use App\Http\Requests\ConvertCurrencyRequest;use App\Util\Currencies;use IlLuminate\Contracts\View\View;use Illuminate\Http\JsonResponse;class CurrencyConverterController extends Controller{public function index(Currencies $currencies): View{return view('currency-converter', ['currencies'->$currencies->alL()]);}public function convert(ConvertCurrencyRequest $request): JsonResponse{$data = $request->validated();//TODO$amount = 999;return response()->json(['amount'->$amount]);}}
We can open the RapidAPI Hub and search for the currency conversion APIs. Simply type in the currency and click search; it gives you a cluster of APIs that you could use.
Hovering over the API enables you to see some information such as endpoints or whether it's a free or a paid API. You have the complete freedom to choose any other API that you like on this API Hub. We use the freemium version for this guide, which means it's paid, but they also have a free tier.
Clicking on the Currency Converter leads you to its documentation interface. Here you can see the available endpoints on the left side, the request information in the middle, and code snippets and response or results on the right.
For testing, you could either choose a free or a paid API. You may also need to be subscribed to one of the API's plans. Clicking on the Pricing tab will take you to the different price plans. The basic plan is free of cost, which gives us a hundred daily requests. Anything above will be charged at that rate, as seen in pro, ultra, and mega packages.
After selecting the price package, we can move to test the API. Clicking on the test button will return a response and show default values. In the Header Parameters, you can see the X-RapidAPI-Key
and X-RapidAPI-Host
. The optional heading contains the format, from, to, and amount parameters.
Besides this, there is a code snippet tab next to it. You can use the snippets to help you integrate this into your application. If you click the dropdown, we see several languages with the snippet available, and PHP is one of them.
Let's click on PHP, but remember that we're not copying or using this snippet in our application because we will be using Laravel. We will make use of the HTTP client rather than using cURL
directly in this guide. However, we will use this snippet later as a reference to enter some details such as headers.
In this step, we will fix our app and integrate it with RapidAPI to do currency conversion. We can begin by using the HTTP facade to use HTTP clients, which helps us make API requests. You can use the constructor method if you feel comfortable with that, but for this guide, we will be using facade.
The first step is to copy the URLs from our code snippet. There is no need to copy the whole URL since we'll pass parameters as an array.
Similarly, to insert parameter values, we could copy and cross-ref the optional parameters variables such as from, to, and amount.
In the next step, we need to pass some headers since we are giving the API key and the host, as shown in the curl code snippet. We can copy the snippet and put it within the withHeaders()
method.
You can simply fix the code by replacing double quotes with single quotes. This way, we can call with headers and pass. We're going to refactor this in later steps.
php
public function convert(ConvertCurrencyRequest $request): JsonResponse{$data = $request->validated();//TODO$amount = 999;Http::withHeaders(['X-rapidapi-host' => 'currency-converter5.p.rapidapi.com','X-rapidapi-key' => 'your-rapidapi-key',])->get('https://currency-converter5.p.rapidapi.com/currency/convert', $data);return response()->json(['amount'->$amount]);}
The above code snippet is inside the CurrencyConverterController class.
The next step involves assigning a response variable. Concerning this, we can throw some Exception
with failed()
to convert the currency message and the status()
.
You don't need to worry about error handling because there are several ways to manage that. For example, you can throw a validation exception with some user-friendly message you want to display to the user. But for this guide, we don't require that.
php
public function convert(ConvertCurrencyRequest $request): JsonResponse{$data = $request->validated();//TODO$amount = 999;$response = Http::withHeaders(['X-rapidapi-host' => 'currency-converter5.p.rapidapi.com','X-rapidapi-key' => 'your-rapidapi-key',])->get('https://currency-converter5.p.rapidapi.com/currency/convert', $data);if ($response->failed()) {throw new \RuntimeException('Failed to convert currency', $response->status());}return response()->json(['amount'->$amount]);}
Now, we can extract the converted amount from JSON that is returned. We can access the rate_for_amount value from the results tab on RapidAPI Hub. We can also access that through the property of the currency code that we're converting it to, i.e., within the "rates" property. This is how we can write code snippet:
php
public function convert(ConvertCurrencyRequest $request): JsonResponse{$data = $request->validated();//TODO$amount = 999;$response = Http::withHeaders(['X-rapidapi-host' => 'currency-converter5.p.rapidapi.com','X-rapidapi-key' => 'your-rapidapi-key',])->get('https://currency-converter5.p.rapidapi.com/currency/convert', $data);if ($response->failed()) {throw new \RuntimeException('Failed to convert currency', $response->status());}$amount = $response->json('rates.' . $data['to'] . '.rate_for_amount');return response()->json(['amount'->$amount]);}
We can test this to make sure it's properly working. Open up the page, enter the random value and convert. You will see that it has changed to the proper value.
Congratulations, we have successfully integrated it with RapidAPI with only a few lines of code. We now have a working currency conversion API.
To integrate multiple APIs, we need to refactor this and make it more flexible. We can do this easily by extracting the code out of the controller into a service class. Subsequently, we need to inject the CurrencyService
class followed by getting the amount
by calling some kind of method on the currencyService
.
You can also pass it as an array if you like, but I prefer to pass them as separate arguments. For example:
php
public function convert(ConvertCurrencyRequest $request, CurrencyService $currencyService): JsonResponse{$data = $request->validated();$amount = $currencyService->convert($data['from'], $data['to'], $data['amount']);$response = Http::withHeaders(['X-rapidapi-host' => 'currency-converter5.p.rapidapi.com','X-rapidapi-key' => your-rapidapi-key',])->get('https://currency-converter5.p.rapidapi.com/currency/convert', $data);if ($response->failed()) {throw new \RuntimeException('Failed to convert currency', $response->status());}$amount = $response->json('rates.' . $data['to'] . '.rate_for_amount');return response()->json(['amount' => $amount]);}
We need to give information to the CurrencyService
class now. Therefore, I will copy and extract the whole code into the CurrencyService
class.
Let's create that class within the Services
namespace. We also need to create the convert method, and within this method, we'll put this code:
php
<?phpnamespace App\Services;use Illuminate\Support\Facades\Http;class CurrencyService{public function convert(string $from, string $to, float $amount): float{$response = Http::withHeaders(['x-rapidapi-host' => 'currency-converter5.p.rapidapi.com','x-rapidapi-key' => 'your-rapidapi-key',])->get('https://currency-converter5.p.rapidapi.com/currency/convert', $data);if ($response->failed()) {throw new \RuntimeException('Failed to convert currency', $response->status());}$amount = $response->json('rates.' . $data['to'] . '.rate_for_amount');return response()->json(['amount' => $amount]);}}
There are minor changes that we need to make now. First of all, we will fix the hard-coded key.
php
<?phpnamespace App\Services;use Illuminate\Support\Facades\Http;class CurrencyService{public function convert(string $from, string $to, float $amount): float{$response = Http::withHeaders(['x-rapidapi-host' => 'currency-converter5.p.rapidapi.com','x-rapidapi-key' => '937a5659e1msh00c2e96ee26c75cp1d5e21jsn9813f557c818',])->get('https://currency-converter5.p.rapidapi.com/currency/convert', compact('from', 'to', 'amount'));if ($response->failed()) {throw new \RuntimeException('Failed to convert currency', $response->status());}$amount = $response->json('rates.' . $to . '.rate_for_amount');return (float) $response->json('rates.'.$to .'rate_for_amount');}}
In an actual application, you would do some error handling on return to ensure that the data actually exists. If it doesn't, maybe throwing some kind of exception can solve this, but it is good enough for this example.
It is time to test this out again and ensure it still works. Let's refresh the page, enter 100 in the value, and click convert. You can see it still works perfectly.
Let's switch back to the code to improve it even further. If we wanted to integrate more than one API, we would be duplicating the code. There is a way we can avoid that and even make it more flexible.
The goal is to extract this into its class. We can inject that class into the constructor, and let's call this class RapidApiService
and promote this to protected property. We need to give host
and url
information in response
. Also, we need to develop private string
and give host
and url
details.
You can improve this further and combine this in a single variable, but I'm going to keep them to properties this way so that I can reuse them in multiple API service classes.
php
<?phpnamespace App\Services;use Illuminate\Support\Facades\Http;class CurrencyService{private string $host = 'currency-converter5.p.rapidapi.com';private string $url = 'https://currency-converter5.p.rapidapi.com/currency/convert';public function _construct(protected RapidApiService $rapidApiService){}public function convert(string $from, string $to, float $amount): float{$response = $this->rapidApiService->get($this->host, $this->url, compact('from', 'to', 'amount'));if ($response->failed()) {throw new \RuntimeException('Failed to convert currency', $response->status());}$amount = $response->json('rates.' . $to . '.rate_for_amount');return (float) $response->json('rates.' . $to . 'rate_for_amount');}}
Now, we will create this class and within the services as well. For this, we need to create a GET method, paste the code, and simply return it. The next step is to replace existing data with the host
, url
with the pramas
. You can visualize here that the RapidAPI service is a wrapper around the HTTP facade or HTTP client. If you prefer, you can inject the client directly into the constructor and use that instead.
php
<?phpnamespace App\Services;use Illuminate\Support\Facades\Http;class RapidApiService{public function get(string $host, string $url, array $params){return Http::withHeaders(['x-rapidapi-host' => $host,'x-rapidapi-key' => 'your-rapidapi-key',])->get($url, $params);}}
The only remaining part is to fix the API key. We can make this possible by accepting the API key in the constructor. Let's create a constructor and accept the API by promoting this to protected property.
php
<?phpnamespace App\Services;use Illuminate\Support\Facades\Http;class RapidApiService{public function _construct(protected string $key){}public function get(string $host, string $url, array $params){return Http::withHeaders(['x-rapidapi-host' => $host,'x-rapidapi-key' => 'your-rapidapi-key',])->get($url, $params);}}
We have to deal with a slight problem at this stage. It is because we expect an API key in the constructor, but we are not directly creating an instance of the RapidAPI service. What can we do to fix this?
One way we can fix this is by using service providers. Let's open the terminal and create a new service provider called 'RapidAPIServiceProvider'.
sh
php artisan make:provider RapidApiServiceProvider
Open that service provider. And within the registered method, we can simply bind the RapidAPI service class.
We pass in the API key here without hard coding it. We'll get this value from the config
file.
php
<?phpuse Illuminate\Support\ServiceProvider;class RapidApiServiceProvider extends ServiceProvider{/*** Register services.** @return void*/public function register(){$this->app->bind(RapidApiService::class,fn () => new RapidApiService(config('app.rapid_api_key')));}/*** Bootstrap services.** @return void*/public function boot(){}}
We also need to register the service provider. Let's open the app.config file, insert the RapidAPI key here, and get the value from the env
variable.
php
<?phpreturn ['rapid_api_key' => env('RAPID_API_KEY'),'name' => env('APP NAME' . 'Laravel'),];
We also need to register the service provider and add the environment variable to EMV file.
We will test this one more time to make sure that it works. Enter the value 100 and click convert. We can also change this to a different value, hit convert, and check that it is still working. So as you can see, it was simple enough to integrate RapidAPI with a Laravel application.
We made it flexible enough to be able to use multiple APIs. That's why we have the RapidApiService
class that simply wraps around the HTTP client. This way, we could create other API service classes like currency service. It can be done by defining the host
and url
, injecting the RapidApiService
into the constructor, and making the proper method call passing the host
and url
. Now, this is a wrapper around the GET method. You could build this up to create another method here for POST requests.
This is pretty much about this guide. We have successfully integrated multiple APIs with the Laravel app using RapidAPI. Try using the same method and develop different kinds of new applications.