Back to all courses
Become a better and more efficient web developer by learning how to use the newly released tools to create, share, test, and document APIs.
The purpose of JavaScript Mastery is to help aspiring and established developers to take their development skills to the next level and build awesome apps."
This article contains information about a recently introduced revolutionary new tool, namely RapidAPI Client
Suppose you've been involved in web development for a while. In that case, you're likely aware that a large portion of our job involves data, such as reading data, writing data, manipulating data, and displaying it in the browser in a meaningful way.
Typically, this data is delivered using REST API Endpoints. In the past, to test REST APIs before connecting the UI to take the data, one had to either query the API through a terminal's command line or use a Graphical User Interface (GUI) like Postmen or Insomnia.
Postman is an API client that simplifies the creation, sharing, testing, and documentation of APIs for developers. It is a fantastic tool for analyzing RESTful APIs created by others or testing the ones you've previously created. It provides a slick user interface for making HTTP queries without writing a large amount of code to evaluate the API's operation.
Postman is a very useful tool that is straightforward and easy to use, and it delivers as promised. The problem with Postman is that it is a separate application from our favorite editor, and switching between applications involves time and effort.
I like to minimize switching apps as much as possible, so incorporating features within my code editor is always appreciated.
Now life has become less complicated. We no longer require additional applications such as Postman or Insomnia. No longer are we need to exit Visual Studio Code to test APIs. This is feasible because RapidAPI has developed a new plugin called RapidAPI Client. It functions identically to Postman but is integrated with Visual Studio Code.
Let me demonstrate how you may apply it in practice.
RapidAPI Client can be used in two distinct ways:
Let's start with the no-code approach so that you can feel the features, and then we'll move swiftly into the coding approach, as I'm confident that's more in line with your interests.
To use the RapidAPI add-on in a no-code method, all you need to do is launch Visual Studio Code. When you click here, you'll be sent to the RapidAPI Client extension for Visual Studio Code. From here, all you need to do is select the install option. You'll be prompted to open it in Visual Studio Code, where we want to send it.
The extension is installed globally, and you should notice the RapidAPI icon on the left sidebar. Since you're installing it for the first time, you may see a welcome screen that guides you through the installation process. However, do not fear; I will walk you through each step.
The first step is to click the sign-in icon in the upper left corner. You'll be asked to sign in, and you'll have to give permission for this. You are now logged in and can begin using RapidAPI.
If you have used RapidAPI previously, you should encounter no problems. It should operate immediately. You will be prompted to do so if you have never created an account.
Now that the window has been reloaded, we can begin using the RapidAPI extension. First, we can locate a random API on the internet. JSON Placeholder API is one of the most popular fake APIs for testing and prototyping. This website's link can be found here.
It is a publicly accessible API with multiple endpoints that we can utilize. For instance, the URL /posts
can retrieve posts. There are other endpoints, i.e., /comments
, /albums
, /photos
, /todos
, and /users
. If you have never used this before, it is an API with a huge quantity of fake data. Fundamentally, it will only contain dummy data.
Let's explore it and employ it instantly within Visual Studio Code. Copying the JSON Placeholder API website's URL (https://jsonplaceholder.typicode.com/) and pasting it into Visual Studio code to add a request is all that is required.
This will be Request 1, and I'll enter the URL into the GET request box and add /post
, i.e., https://jsonplaceholder.typicode.com/posts
. With this information, you can instantly click the send button. You will observe a detailed API response within your Visual Studio Code.
Here we can enter Get Posts as the name and Fetch 100 posts as the description. Now that we have tested a single API endpoint, we can immediately see the JSON we receive. Within our code, we are also aware of the data we're working with without the need for console logging, writing additional queries, etc. Additionally, we can pass additional Headers, Queries, Bodies, and Auth.
Since we already have one request, let's put in a second one. Let's click on requests and retrieve information such as users. Therefore, I will again paste the same URL with /users
, i.e., https://jsonplaceholder.typicode.com/users
, and we may now click the send button.
You'll find that we have complete information on 100 users. Once again, we'll enter the name, Get Users, and the brief description, Fetch 100 users.
We can also construct typescript interfaces, which is a wonderful feature. This is handy if you have recently started working with typescript.
We only need to click the small code button in the bottom right corner to construct an automatically generated whole interface. This will generate a new file, including all interfaces
You can also observe that the RapidAPI Client identified this immediately, and we have all types listed below. Therefore, if you work with typescript, this will be useful.
We've consumed and modified this API. It'll return modified data. Now, you want to publish this API for use in other apps.
RapidAPI made it quite simple. To create or open a project, you can launch RapidAPI Client from the sidebar and click this button at the upper left. After clicking the button, you may immediately start a new project on your RapidAPI (personal) account.
We can enter the project's name, such as JSON placeholder, and hit enter. This will automatically create a project, and we will be prompted to synchronize our local project with the new JSON Placeholder project.
You can now observe that a JSON placeholder (online) is beginning to appear in front of the Project.
The best part about this is that if you navigate to RapidAPI Studio and enter in with the same account that you used to get into Visual Studio Code, it will instantly sync your API, and all of the endpoints that you construct will begin to appear on the platform.
Also, you may list your API on the RapidAPI Hub so that others can utilize it. This is something that I'm going to show you how to do once we launch our own real API, which will be in the next section of this guide, and it involves using the RapidAPI extension, but now with coding.
To begin with, we'll use one of the APIs, the currency converter, rather than building our own actual API from scratch. So let's create a new project to learn how to properly test your real APIs using the RapidAPI Client.
Create a new project by clicking the icon at the top. The name of the RapidAPI personal project we intend to construct is the currency converter.
It's going to create it immediately, and it's asking if we want to sync our local project with the currency converter since we haven't yet deleted the previous one.
We have transitioned to the currency converter project and can now accept new requests. However, before we proceed, let's establish a new empty folder on our desktop. It will be called currency_converter. Let’s drag and drop it directly into Visual Studio Code.
Once it's in place, we can create a new file named index.js
. Since this guide teaches you how to design, publish, and test your APIs as efficiently as possible, we do not need to cover the complete process of creating an API.
For this reason, I've already written a small API for testing purposes. This API consists of two distinct functions and a third function that is used to test the API's functionality. The initial method retrieves the countries from the REST API for countries. In particular, it retrieves them based on the currency code they provide.
The second function converts currency. In a way, this API is a currency converter and indicates in which countries you can spend the money you convert to your currency. I utilize the Math.random()
function to generate random integers so that you don't have to look for any additional API keys for currency conversion.
js
import axios from 'axios';const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};convertCurrency('USD', 'CHF', 20).then(data => console.log(data)).catch(error => console.log(error));
Now that we have our API available, please run the following command in the terminal.
sh
npm init -y
This will generate a generic package.json
file. Since we're currently utilizing import syntax, we'll need to add an additional line type:module
. This can be written as follows:
json
{"name": "currency_converter","version": "1.0.0","description": "","type": "module","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC"}
We'll also have to run following command in terminal:
sh
npm install axios
It is because we will use Axios to make the API calls. Now, if we wish to execute our API once, we can enter the following command:
sh
node index.js
The description appears, "20 USD is worth 99.35 CHF. You can spend these in the following countries: Liechtenstein, Switzerland". So now we know our API works, but it's not an API as of yet.
It's just a series of two function declarations and then one function call. We're not hosting this anywhere. We cannot call it again; we just called it once by running our code. So what we can do to turn this into your real API by installing express
.
Go ahead and run the following command in the terminal:
sh
npm install express
Since Express is installed, we can import it and create at least one endpoint. Let's write app.get()
and provide it with a callback function. Inside the callback function, we have a request and a response. After that, we always have to return something.
It will be res.send()
; in this case, we want to send some JSON. In this instance, we want to send the result of the convertCurrency
function.
Before we send any data, we'll have to call the convertCurrency
to get the information we want to send back from the API. We can add the async
keyword because we want to call this function from our app.get()
.
Since the message is being returned, we can add const message
and assign it the value of convertCurrency ('USD', 'CHF', 20)
. Then, this will be the identical call to our API, but we want to append await
to it.
In this instance, we're working with dummy data, but we'll soon test it using our API client inside of Visual Studio Code to make it work with dynamic parameters that we pass to it, and now we can send a message using res.send(message)
.
With that, we no longer need the rest of the function because we turned this from a function call and a single file to an API. But for this to be an API, there is just one final part missing: app.listen()
. We need to make this API listen somewhere on a specific port i.e. 5000.
We need to have a callback function where we're going to simply console.log()
and say something like Server is listening on port 5000.
js
import axios from 'axios';import express from 'express';const app = express();const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};app.get('/', async (req, res) => {const message = await convertCurrency('USD', 'CHF', 20);res.send(message);});app.listen(5000, () => {console.log('Server is listening on port 5000');});
Now that we've established a small API in the proper way, it's time to test it. Therefore, we may launch the RapidAPI Client and initiate the creation of a new request.
The name of the request will be something like Get Exchange Rate, and in the GET search bar, we can simply type localhost:5000. Before clicking Send, we need to open our terminal and run the following command:
sh
node index.js
This will enable our server to operate on port 5000. Just before pressing the send button, let's add the http
to create a real URL, such as http://localhost:500, and click the send button.
We may also observe the status of 200 OK, the response size, the request, and the response itself. Currently, responses are received in web format. It is similar to HTML, but this is not what an API should provide.
For this, we can go back to our code and say res.json()
instead of res.send()
. This is going to make sure to return the data in JSON format.
js
import axios from 'axios';import express from 'express';const app = express();const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};app.get('/', async (req, res) => {const message = await convertCurrency('USD', 'CHF', 20);res.json(message);});app.listen(5000),() => {console.log('Server is listening on port 5000');};
Now for the changes to take effect. We can restart the server:
sh
node index.js
Now, if we rerun our request, we can see that we receive a JSON Tree or JSON text, which is much easier to understand. In this case, we only have a single string, but often you'll have objects with real data, so you'll be able to read through them simply.
Let's add some additional functionality to our API so that we can modify the currency we want to exchange, fromCurrency
, we can exchange toCurrency
, and then the total amount
. We can accomplish this by passing query parameters to our API.
These will be populated once we make our API call, and now we can simply exchange the static variables with these newly created variables fromCurrency
, toCurrency
, and the amount
.
js
import axios from 'axios';import express from 'express';const app = express();const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};app.get('/', async (req, res) => {const {fromCurrency, toCurrency, amount} = req.query;const message = await convertCurrency(fromCurrency, toCurrency, amount);res.json(message);});app.listen(5000),() => {console.log('Server is listening on port 5000');};
The next step is to return to Visual Studio Code, where you may enter query parameters using the wonderfully convenient dedicated query section.
You may enter fromCurrency and the value USD in Query Param. Similarly, you can enter toCurrency and the value CHF in the second row. Finally, you can enter the amount, which will likely be 20.
Now let's re-run our server by running the following command:
sh
node index.js
After that, click the send button. As you can see, our headers are returned, and the query was automatically populated within our info. We have also received the response, "USD is equivalent to 170.7 CHF." We can also verify it by switching the countries where we can spend that money.
Let's convert toCurrency to HRK, the currency used in Croatia. Simply clicking Send reveals that we can only spend this currency in Croatia, indicating that our API test was successful.
We can now document it by saying Get Exchange Rate -> Accepts fromCurrency, toCurrency, amount. Our API is currently accessible only on our local machine. Now that we can access it on localhost:5000, let's deploy it so that users around the globe may access it.
Let's close a RapidAPI Client and open up our terminal. Our API will be deployed using Heroku. Heroku is a free solution that facilitates the deployment of APIs. Once you have downloaded it, we may begin the installation.
Let's add one additional file to our file tree, and that file is called Procfile
. Instead of there
, we can write:
sh
web: node index.js
Let’s initialise a git project by running the following command:
sh
git init
We can create a .gitignore
file and then write the following inside it:
sh
/node_modules
We have to create this file because we don't want to push all the node modules when we are deploying our application.
Let’s log into Heroku by running the following command in the terminal:
sh
heroku login
If Heroku was installed correctly, this should operate without a hitch, and we can press any key to open the application in a web browser. Currently, login is required.
You may log in, or if you're new to Heroku, you can create an account. Once you have successfully logged in, you will see this screen, and we can then return to the code.
Now that we are logged in, we can run:
sh
# create heroku projectheroku create# add files to staging areagit add# create commitgit commit-m 'first comit'# push files to herokugit push heroku masterheroku open
Unfortunately if we now open it, we will only find a single application. I quickly figured out what is the reason. Instead of simply deploying to localhost:5000, we must use the automatically produced Heroku variable, which will be process.env.PORT
js
import axios from 'axios';import express from 'express';const app = express();const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};app.get('/', async (req, res) => {const {fromCurrency, toCurrency, amount} = req.query;const message = await convertCurrency(fromCurrency, toCurrency, amount);res.json(message);});app.listen(process.env.PORT),() => {console.log('Server is listening on port 5000');};
Now we can simply go through the process of pushing the changes one more time.
sh
git add .git commit -m 'second commit'git push heroku masterheroku open
Let's change our endpoints just a bit alongside changing the ports. So here we're always accepting these fromCurrency
, toCurrency
and the amount
. But what if a person doesn't send them? In this case, we can simply write if()
block like this:
js
import axios from 'axios';import express from 'express';const app = express();const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};app.get('/', async (req, res) => {const {fromCurrency, toCurrency, amount} = req.query;if (!fromCurrency || toCurrrency || !amount) {res.send('Please provide all the required parameters');} else {const message = await convertCurrency(fromCurrency, toCurrency, amount);res.json(message);}});app.listen(process.env.PORT, () => {console.log('Server is listening on port 5000');});
Now let's structure this properly and let's go through the process of pushing this one more time.
sh
git add .git commit -m 'third commit'git push heroku masterheroku open
The application has now loaded on our newly formed endpoint, and we can ping it from our RapidAPI Client. Therefore, let us copy this newly formed URL: https://warm-island-300783.herokuapp.com/. Back in our code, we can now navigate to get the exchange rate and replace the URL with the newly-created Heroku URL. Let's then hit send.
We received the response. Now that we have designed, tested, and deployed our API, it is time to publish it to the RapidAPI Hub so that others can utilize it. And if you recall correctly, the RapidAPI Client immediately syncs with the RapidAPI Studio. Therefore, if we go to our RapidAPI studio, the currency converter will be there.
Before adding all of the essential Hub listing information, I've tweaked the tests tab to demonstrate that RapidAPI Studio supports automated testing. So allow me to demonstrate how to achieve that.
First, we'll click the Create Test button. Let's give this test a name like Automated Test. You will be directly redirected to that test, where we will add our first step. You will have other alternatives for automating your tests, but for this example, let's utilize a straightforward HTTP GET request.
Let's go to our URL, and that URL "https://warm-island-300783.herokuapp.com/" is going to be the link to our deployed API. Let's just go to the home route without passing any variables, and click Save and Run. As you can see, the test succeeded. We can also view more information.
Let's return to the Hub listing to include all of our API details. You must include general information if you want many individuals to utilize your API.
You can begin by adding an icon. After that, we can add a category; as this is a currency converter, let's choose Financial. In the description, we can state, A simple API that allows you to exchange a specific amount from one currency to another. We can now validate that we have permission to publish this API.
We also need to add our base URL, i.e., "https://warm-island-300783.herokuapp.com/". It is the link to our deployed Heroku application. Once you add it, you can click Save.
The application is successfully updated. Now, you can scroll to the top and click on View in Hub. The Currency Converter API is live on the RapidAPI Hub amongst tens of thousands of other APIs.
We can improve the usability of the API. For instance, we can create an endpoint and describe the queries. We can also add a pricing section so that you can profit from it.
Let's return to RapidAPI Studio and navigate to the Endpoints page.
We can now add the initial REST endpoint. That will be Exchange Currency, and you can add a forward slash (/) to the GET search bar. We send query parameters, i.e., fromCurrency and toCurrency. Finally, the amount can be set to some sample values, such as EUR, USD, and then 100. Following that, check the Required boxes.
RapidAPI platform will immediately provide you with a clean way of how other people can immediately consume your API. Before saving it, we can scroll up and add a description.
I'm going to use the same sentence we used before, i.e., A simple API that allows you to exchange a specific amount from one currency to another and I'm going to click save. With that said, our endpoint is added.
Let's head to monetize. Here, you can select various API plans, including Basic, Pro, and Ultra. So with the PRO Plan, let's set the quota to 1,000 requests each month. Then it will cost $0.01 or 1 cent per further request. We can also convert this to a monthly membership for ten dollars.
Let's reload the page and return to our currency converter API on the RapidAPI Hub. As seen, an endpoint emerged on the page's left side.
In addition, we can see that we are required to pass certain parameters, with clear instructions on how to do so. We offer a pricing section so that users of your API can subscribe and pay you directly.
Now, if we return to the endpoints page, we can click the Test Endpoint button. This will execute our endpoint with the given parameters.
It is evident that we do not obtain the desired outcome, but we are fortunate that we have reached this point. Because we are now aware of the final step necessary to publish our API correctly.
In our case, the issue is that we are returning a message rather than JSON format; however, it must be in JSON format. Therefore, while working with APIs, you should always return a JSON, which is JavaScript object notation.
In other words, it's an object that requires a key and a value to function properly. We can compose the following instruction:
js
import axios from 'axios';import express from 'express';const app = express();const getCountries = async currencyCode => {try {const response = await axios.get(`https://restcountries.com/v3.1/currency/${currencyCode}`);return response.data.map(country => country.name.common);} catch (error) {throw new Error(`Unable to get countries that use ${currencyCode}`);}};const convertCurrency = async (fromCurrency, toCurrency, amount) => {const countries = await getCountries(toCurrency);const convertedAmount = (amount * Math.random() * 11).toFixed(2);return `${amount} ${fromCurrency} is worth ${convertedAmount} ${toCurrency}. You can spend these in the following countries: ${countries}`;};app.get('/', async (req, res) => {const {fromCurrency, toCurrency, amount} = req.query;if (!fromCurrency || toCurrrency || !amount) {res.send({message: 'Please provide all the required parameters'});} else {const message = await convertCurrency(fromCurrency, toCurrency, amount);res.json({message});}});app.listen(process.env.PORT, () => {console.log('Server is listening on port 5000');});
If we now redeploy this, our API is going to work. So run this again:
sh
git add .git commit -m 'fourth comit'git push heroku masterheroku open
Our API has been redeployed, and I will now click Test Endpoint. As you can see, we now receive a message, which has a single text stating that 100 EUR is equivalent to 40 USD. Again, the numbers are generated at random, and we can then spend them in the following countries.
With that, we completed the journey back to the beginning. Installing the RapidAPI Client, understanding how to utilize it to test our APIs, and then diving into the RapidAPI Studio, which automatically syncs to the RapidAPI Client, were all steps we have covered in this guide. Go ahead and try it out!