Back to all courses
Let's say you have an application that uses multiple APIs from various platforms. Each API has its own key and its own way of managing access. What if I told you that there's a platform where you can manage all of your APIs in one spot? We're going to build an app that consumes multiple APIs using RapidAPI to see how easy it is to use. We'll create a quick project by using Vite.js and Tailwind CSS, then use RapidAPI to connect to 4 APIs and consume their data.
I create the best content I possibly can to give away free. My tutorials are generally about web development and include coding languages such as HTML, CSS, Sass, JavaScript, and TypeScript. Subscribe to my YouTube channel for the latest content.
This guide will explain the exciting process of managing all of your APIs in a single platform. We'll learn this by building an application that consumes multiple APIs using RapidAPI.
At times, you have to use an application that uses multiple APIs from various platforms. Since each API has its own key and its way of managing access, this is where this guide comes in handy.
Before starting, let's first look at the website of RapidAPI. It's the next-generation API platform where you can find, connect to, and manage thousands of APIs.
It is the world's largest API Hub and has all the APIs you need in one place. You can access as many APIs as your application requires using a single account API key and SDK.
There are multiple APIs that you can use for your app-building. Some of the top APIs included on this platform is Twilio, Microsoft, Google, SendGrid, TeleSign, and many more.
You can also manage and monitor the performance of your APIs from the dashboard. It will provide quick insights into managing and visualizing various responses and requests made to different APIs.
Let's explore the RapidAPI Hub website, where we can discover different API categories, which include recommended and popular APIs. You can open the website through this link RapidAPI Hub
We can search for any required API in the search bar at the top. Let's search for “geolocation API”. Let’s go with IP Geo Location API.
When you open its API page, its documentation interface pops up. This will provide us with a playground that we can use to test our API.
You can see that it is a freemium API. We can check the details in the Pricing option. We'll use the Basic plan, which is free and includes 500 requests a day, which is perfect for development. You can upgrade to a paid plan once you reach the production stage.
Let's go back to Endpoints for further processing. We can click the Test Endpoint button and look at the results. You will see the user's IP address, longitude, and latitude area. This will show you the location from where you are connected. Since I am using a VPN in this case, it shows Madrid's location in Spain.
Let's go back to code snippets to see how we can integrate this into our application. There are many different languages that we can choose. The default is Node.js
using Axios, but we'll use (JavaScript) fetch
for this guide. Now, if we click the Copy Code button, we can paste it into our JavaScript file.
We will now build a weather app using the IP Geo Location API and some other APIs. For this, we will get our geolocation data to determine our users' city. After that, we'll pass that city to another API that gives us the weather data for that city. Let's see this whole process in easy steps.
We'll open the terminal in Visual Studio Code. We'll write the following command and install it in the current directory :
sh
npm init @vitejs/app .
After that, we will give the package name rapidapi-demo
. For Select a framework
, we can choose vanilla JavaScript.
Once the above process is executed, we can install packages by simply using the following command:
sh
npm install
Since we'll use tailwind, we can install this by writing:
sh
npm i -D tailwindcss@latest
Then we'll create the files that we need for tailwind. So we can write:
sh
npx tailwindcss init -p
After that, we'll go to tailwind.config.js
and define the files we want to purge
when we build.
js
module.exports = {purge: ['./index.html', './**/*.js'],darkMode: false, // or 'media or 'class'theme: {extend: {}},variants: {extend: {}},plugins: []};
Following that, we'll import our tailwind details in the styles.css
.
css
#app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;text-align: center;color: #2c3e50;margin-top: 60px;}
Now let's work on the index.html
. Let’s change the title to RapidAPI Demo. I have also pasted some HTML here.
html
<!DOCTYPE html><html lang="en"><head><meta chorset="UTF-8" /><link rel="icon" type="image/svg+xml" href="favicon.svg" /><meta name="viewport" content="width-device-width, initial-scale=1.0" /><title>RapidAPI Demo</title></head><body class="bg-gray-100"><h1 class="text-bold text-6xl text-center p-8">Mixed API Feed</h1><divid="app"class="min-h-screen flex flex-col justify-center items-center gap-2"></div><script type="module" src="/main.js"></script></body></html>
We have used several tailwind classes in the above code snippet and have also created a header that says mixed API feed.
In the next steps, we will import the weather data. Then we'll put all the data into this div
with the id
of app
. So it is pretty simple. Everything else that we'll be doing in the main.js.
Let's open up our main.js,
and we'll remove the JavaScript that comes with Vite. After that, we'll set up our function so we can easily reuse them for multiple APIs. The first thing that we'll need is our RapidAPI key. So, we'll import that from an environmental variable and Vite. However, If we want an environmental variable to show up to the client, we have to prefix it with the underscore.
js
import './style.css'const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;
We'll now create a new .env
file, which will contain VITE_RAPIDAPI_KEY
, and its value will be equal to our API key. We can copy the RapidAPI key from our code snippet at our RapidAPI dashboard. Since it is a personal key, I will refresh it before publishing this guide.
js
VITE_RAPIDAPI_KEY=your-rapidapi-key
Next, we'll set up a function called getData
, which will be an async
function. It will accept a URL and a host as parameters. After this, we'll create a response variable that will await
fetch
, which will fetch the URL. Within that, we'll have a method of GET
, and then we'll have some headers. We'll accept application/json
.This is where we'll be passing our RapidAPI key and RapidAPI host.
After that, we'll check if the response is okay, and if it's not, we'll throw an Error
. Lastly, we'll return await response.json
. So with this function, we can use our RapidAPI key to connect to multiple APIs.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};
The next step is to connect this to the IP Geo Location API. We can do this by creating a couple of variables called GEOLOCATION_URL
, and a GEOLOCATION_HOST
.
We can get this information from our code snippet at RapidAPI Hub. We'll copy both the RapidAPI Host and RapidAPI URL from the code snippet and paste them into the main.js
file. This is how we'll set the values of our GEOLOCATION_URL
, and a GEOLOCATION_HOST
.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL = 'https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};
Let's create the main function that will call our APIs. We'll create a function called runAPIQueries
, which will be an async
function. We'll write the city name here and create a variable called geoData
. This will await
our getData
function we created earlier.
We'll pass in the GEOLOCATION_URL
and our GEOLOCATION_HOST
in the getData
function. After that, we'll console.log
the data to see what we get. Of course, we also need to initiate the function we'll call at the end.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);};runApiQueries();
Let's go ahead and run this and see what we have. Let's open up the terminal and write:
sh
npm run dev
We can see that a host server is running on localhost 3000. If we open that up, we have our Mixed API feed header. On the console, we will see the result of the API call. There is an object, and if we open it, we will find the city key which we are looking for. Inside it, we have the city name.
Now let’s use a weather API to get weather data for the city. Back in RapidAPI, let's search for the weather. We'll use Open Weather Map API Open Weather API, so open it up; all we need is the URL and the host information. We'll copy these and pass this information into our runAPIQueries()
.
Let's open our weather app, and we can copy the URL and Host information from the code snippet. We will go back to the main.js
file and add two variables i.e., const WEATHER_URL
and const WEATHER_HOST
. To incorporate weather information, we can write const weatherData
and make it equal to await getData()
inside the runApiQueries
function.
Now, we need to pass in our geolocation URL and our host. We can do this by adding our Weather_URL
and append to that with geo data.city.name
.
js
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const WEATHER_URL = 'https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);};runApiQueries();
The next step is to update the UI with the console data. We'll go back to VSCode and create a constant called app
to get the app
id element. . This is the element where we will add our UI data. We will then set the innerHTML
of the app
constant to write HTML. We have added a div that has several Tailwind classes. Then within that, we're going to have our weatherData.weather[0]main
.
After that, we will add weather temperature followed by weather description. This is where it gives weather information such as partly cloudy with a chance of rain or something like that. Then we have an svg
and our weatherData.name
, which will be the city name. Following this, we will pull in the weather data and icon, showing a rain cloud, a sun, or whatever the current condition is.
jsx
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com';const WEATHER_URL = 'https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="flex bg-blue-500 text-white rounded py-2 px-8 w-full max-w-2xl items-center border-2 border-blue-300 shadow-lg"><div class="flex flex-col flex-grow"><div class="text-md">${weatherData.weather[0].main}</div><div class="flex h-max items-center"><div class="font-medium text-6xl">${parseInt(weatherData.main.temp)}°</div><divclass="flex flex-col ml-4 pl-4 border-l-2 border-blue-400"><div>${weatherData.weather[0].description.toUpperCase()}</div><div class="flex"><svgxmlns="http://www.w3.org/2000/svg"class="h-5 w-5"viewBox="0 0 20 20"fill="currentColor"><pathfill-rule="evenodd"d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"clip-rule="evenodd"/></svg><span class="pl-1">${weatherData.name}</span><div></div></div></div><imgclass="self-center inline-flex items-center justify-center rounded-lg h-28 w-28"src="http: //openweathermap.org/img/wn/${weatherData.weather[0].icon}@a2x. Png"alt="weather icon"/></div></div></div>`;};runApiQueries();
Let's go ahead and save that, and we'll go back to our app and see if it works. We can see information such as clouds, current temperature, and location successfully deployed in our feed.
Let's add another API to the app. We can do something a little more fun this time. If we write Chuck Norris, it will give us Chuck Norris API that provides us with some Chuck Norris jokes.
Like the previous API, we will copy the URL and Host information from Code Snippet and go back to VSCode.
Let's create some variables for those and paste the information we copied from the Code snippet. We want a random joke under the category of dev
. It will be very similar to the way we did the weather data. After that, we have to create a variable called chuckData
. It will be equal to getData
, which we will await. Then we will pass in our CHUCK_NORRIS_URL
and our CHUCK_NORRIS_HOST
and console.log
the data.
Once we get the data, we'll update the UI. We'll add our chuckData.icon_url
and then our chuckData.value
, which will be the joke we are looking for.
jsx
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com ';const WEATHER_URL ='https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const CHUCK_NORRIS_URL ='https://matchilling-chuck-norris-jokes-vl.p.rapidapi.com/jokes/random? category=dev';const CHUCK_NORRIS_HOST = 'matchilling-chuck-norris-jokes-v1.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="flex bg-blue-500 text-white rounded py-2 px-8 w-full max-w-2xl items-center border-2 border-blue-300 shadow-lg"><div class="flex flex-col flex-grow"><div class="text-md">${weatherData.weather[0].main}</div><div class="flex h-max items-center"><div class="font-medium text-6xl">${parseInt(weatherData.main.temp)}°</div><divclass="flex flex-col ml-4 pl-4 border-l-2 border-blue-400"><div>${weatherData.weather[0].description.toUpperCase()}</div><div class="flex"><svgxmlns="http://www.w3.org/2000/svg"class="h-5 w-5"viewBox="0 0 20 20"fill="currentColor"><pathfill-rule="evenodd"d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"clip-rule="evenodd"/></svg><span class="pl-1">${weatherData.name}</span><div></div></div></div><imgclass="self-center inline-flex items-center justify-center rounded-lg h-28 w-28"src="http://openweathermap.org/img/wn/${weatherData.weather[0].icon}@a2x.png"alt="weather icon"/></div></div></div>`;// GET - CHUCR NORRIS JOKESconst chuckData = await getData(CHUCK_NORRIS_URL, CHUCK_NORRIS_HOST);console.log(chuckData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="max-w-2xl w-full bg-purple-400 border-2 border-gray-300 shadow-lg p-6 rounded-md tracking-wide"><div class="flex items-center mb-4"><img alt="avatar" class="W-20" src="${chuckData.icon_url}" /><div class="leading-5 ml-6 sm"><h4 class="text-xl font-semibold">Chuck Norris</h4><h5 class="font-semibold text-purple-800">Boss</h5></div></div><div class="text-center"><q class="italic text-white text-lg">${chuckData.value}</q></div></div>`;};runApiQueries();
Let's save that, and we can see our weather data, and we've got this fun Chuck Norris joke.
It is time to add one more API. Let’s return to the RapidAPI Hub and search for “NewsData API”. We will use this NewsData API and integrate it with the previous three APIs.
Again, we just need to get its URL and host. We'll copy this information from the code snippet and paste it into VSCode inside two new variables.
Back in the main function under the chuck data, we will create another constant called newsData
and assign getData
to it, which we will await
Then we pass in our URL, and our host, and finally, we're going to console.log
the data. Let’s go back to our app and look at the API response in the console.
Since the news data is an array, we'll do forEach
through which we will get each article
, which we'll add to our inner HTML of the app. For the article
, we'll get the media_url
to get that cover image. Then after that, we'll get our title
and remember it had paragraph tags, which we'll remove.
We'll do the same for the excerpt, and that should be it.
jsx
import './style.css';const RAPIDAPI_KEY = import.meta.env.VITE_RAPIDAPI_KEY;const GEOLOCATION_URL ='https://ip-geo-location.p.rapidapi.com/ip/check?format=json';const GEOLOCATION_HOST = 'ip-geo-location.p.rapiidapi.com ';const WEATHER_URL ='https://community-open-weather-map.p.rapidapi.com/weather?units=imperial&q=';const WEATHER_HOST = 'community-open-weather-map.p.rapidapi.com';const CHUCK_NORRIS_URL ='https://matchilling-chuck-norris-jokes-vl.p.rapidapi.com/jokes/random? category=dev';const CHUCK_NORRIS_HOST = 'matchilling-chuck-norris-jokes-v1.p.rapidapi.com';const NEWS_URL = 'https://newsdata2.p.rapidapi.com/sources';const NEWS_HOST = 'newsdata2.p.rapidapi.com';const getData = async (url, host) => {const response = await fetch(url, {method: 'GET',headers: {accept: 'application/json','x-rapidapi-key': RAPIDAPI_KEY,'x-rapidapi-host': host}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}return await response.json();};const runApiQueries = async () => {// GET CITY NAMEconst geoData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);console.log(geoData);// GET WEATHER DATA BY CITYconst weatherData = await getData(WEATHER_URL + geoData.city.name,WEATHER_HOST);console.log(weatherData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="flex bg-blue-500 text-white rounded py-2 px-8 w-full max-w-2xl items-center border-2 border-blue-300 shadow-lg"><div class="flex flex-col flex-grow"><div class="text-md">${weatherData.weather[0].main}</div><div class="flex h-max items-center"><div class="font-medium text-6xl">${parseInt(weatherData.main.temp)}°</div><divclass="flex flex-col ml-4 pl-4 border-l-2 border-blue-400"><div>${weatherData.weather[0].description.toUpperCase()}</div><div class="flex"><svgxmlns="http://www.w3.org/2000/svg"class="h-5 w-5"viewBox="0 0 20 20"fill="currentColor"><pathfill-rule="evenodd"d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z"clip-rule="evenodd"/></svg><span class="pl-1">${weatherData.name}</span><div></div></div></div><imgclass="self-center inline-flex items-center justify-center rounded-lg h-28 w-28"src="http://openweathermap.org/img/wn/${weatherData.weather[0].icon}@a2x.png"alt="weather icon"/></div></div></div>`;// GET - CHUCR NORRIS JOKESconst chuckData = await getData(CHUCK_NORRIS_URL, CHUCK_NORRIS_HOST);console.log(chuckData);// UPDATE UI WITH DATAapp.innerHTML += /*html*/ `<divclass="max-w-2xl w-full bg-purple-400 border-2 border-gray-300 shadow-lg p-6 rounded-md tracking-wide"><div class="flex items-center mb-4"><img alt="avatar" class="W-20" src="${chuckData.icon_url}" /><div class="leading-5 ml-6 sm"><h4 class="text-xl font-semibold">Chuck Norris</h4><h5 class="font-semibold text-purple-800">Boss</h5></div></div><div class="text-center"><q class="italic text-white text-lg">${chuckData.value}</q></div></div>`;// GET NEWS DATAconst newsData = await getData(NEWS_URL, NEWS_HOST);console.log(newsData);newsData.forEach(article => {app.innerHTML += /*html*/ `<div class="max-w-2xl w-full flex border-2-border-gray-300-shadow-lg"><imgclass="h-autow w-48 flex-none rounded-l object-cover"src=${article.jetpack_featured_media_url}alt="Image Description"/><divclass="bg-white rounded-r p-4 flex-flex-col justify-between leading-normal"><div class="mb-0"><div class="text-black font-bold text-xl mb-0">${article.title.rendered.replace('<p>', '').replace('</p>', ' ')}</div><pclass="text-grey-darker text-sm overflow-hidden overflow-ellipsis may-h-24">${article.excerpt.rendered.replace('<p>', ' ').replace('</p>', ' ')}</p></div></div></div>`;});};runApiQueries();
Let's go ahead and save it and go back to the app.
All right. We have our Weather, Chuck Norris, and our NewsData APIs.
That’s it. Using RapidAPI, we have successfully implemented four different APIs quickly and easily using a single API key and a single management dashboard.