What is a REST API?
Let’s break the term REST API down into its acronyms starting with ‘API’. Many definitions exist for the different types of application programming interface’s (APIs) but my favorite definition is;
…an API provides interactions between one software and another, but not users.
REST APIs serve the simple purpose of connecting computer services on the internet. However, what makes an API RESTful depends on the API’s implementation. To be clear, REST is an architectural style that does not follow a standard. Therefore, you can expect some variances when using different APIs.
HTTP Methods
One similarity between APIs is that they all work with the same set of HTTP methods. The methods include, but are not limited to;
For a breakdown of the difference between PUT and PATCH check out this article.
We will focus on GET and POST in this article because they are the most common. Sending a GET request is simple and is done frequently. For example, entering a URL into your browser GETs the index.html (assuming that the URL has no added parameters, i.e www.example.com) and returns the page. The returned data is called the payload.
API Payloads
Payloads can be formatted in HTML, XML, or JSON. It has become increasingly common to implement APIs that deliver JSON payloads. JSON stands for JavaScript Object Notation. A simple JSON object looks like;
{ "parameter1": { "nestedParameter": "value" }, "parameter2": "value2" }
Values can be accessed on the object using dot-notation. For example, if the object is named data
, the nested parameter value could be accessed with data.parameter1.nestedParameter
.
REST
‘REST’ stands for Representation State Transfer. One of the reasons someone would want to implement a REST API is to grow operations faster. This can happen because the service is not constantly connected to the other web service. The connection occurs only at the time the resource is needed.
Consequently, there is not a shared state between web services and the state is transferred between the web services with requests. “State” can be loosely referred to as the web service’s application values in this scenario.
All the operations of a REST API are stateless. You can think of each request as being a fresh new request.
To learn more about RESTful APIs you can visit the Wikipedia page by clicking here.
Advantages of REST APIs
RapidAPI is a platform for accessing web-based REST APIs. As defined previously, APIs connect services. In addition to services, APIs allow an application to access external data.
In theory, utilizing REST APIs can boost a web service’s functionality and effectiveness by allowing the service to quickly gain access to code and data. A developer could connect to financial data, or have access to machine learning algorithms with a few lines of code in comparison to hundreds of hours of programming time to develop the service on their own.
In later sections, we’ll explore the simplicity of sending HTTP requests to external REST APIs with Node.js.
Node.js Overview
Node.js is not a language, but rather a runtime that allows the use of JavaScript on the server. Developers traditionally use JavaScript for front-end code like manipulating web page elements and sending HTTP requests.
Furthermore, it can be desirable to write with the same language for both front-end and back end, but it is not the only feature. Node.js is asynchronous and event-driven. It has ‘non-blocking’ capabilities that allow it to scale to a large number of requests without being slowed down by a few expensive connections.
Nonblocking means that a function can be called and while that function is running, the application can move on and execute other code or respond to more requests.
Promise
The
Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.–MDN
Promises are created when we execute asynchronous code. This is common when using REST APIs.
To understand what a Promise does, let’s consider this sequence of events:
- An HTTP request is sent for external data and a promise Promise object is created
- 3 seconds (this is just an example duration) elapse while the data is retrieved over the network. Other Javascript may be executed.
- The HTTP response is received and the Promise is fulfilled with requested data
This can be confusing at first but is very powerful once understood. A great resource for learning more about Promises is the MDN web documents explanation of a Promise. In the next section, I will list my favorite resources for getting started with Node.js and Javascript. However, if Javascript is not new to you, it can still help refresh your knowledge.
Best resources for learning Node.js?
There is an overwhelming amount of material on the internet for learning programming skills. I know how difficult it can be to find tutorials that are worth your time. Therefore, I will list a few of my favorite resources that I have personally used (some that I still use):
New to programming and Javascript
- freeCodeCamp – start at the beginning
- freeCodeCamp – Javascript and Data Structures tutorial and exercises
- Mozilla Development Network (MDN) – Javascript basics
New to Node.js
- MDN – What is Node and What is Express? – 7 part intro-to-deployment tutorial
- The Complete Node.js Developer Course (3rd Edition) by Andrew Mead on Udemy – 34-hour video course
Those are all great resources for learning or improving your understanding of Javascript and Node.js. The examples below won’t cover all the techniques used in the code, so be sure to use the references above to deepen your understanding.
How To Use An API with Node.js
In this section, we will build a small program that calls an API in Node.js. Later, I’ll introduce an example application that hopefully can show how an API call can fit into a larger web application.
Prerequisites
- Node.js installed on your machine
- Understanding of how to open a terminal, or command-line on your machine
- Internet connection
- Code editor (I am using Visual Studio Code)
1. Sign Up For a Free Account on RapidAPI
To subscribe to APIs, you will need an account. Visit RapidAPI to get signed up if you haven’t already!
2. Subscribe to an API
Notice I have already subscribed to the Basic plan, therefore I have a link to Manage and View Usage that takes me to the developer dashboard.
You can track your API usage on the dashboard in case you have concerns about approaching your quota for any of the APIs that you subscribe to.
3. Set-Up Project
Open up a new terminal.
In the terminal run the following commands.
$ mkdir node-api-call $ cd node-api-call $ npm init -y
The commands create a new directory, move the terminal inside that directory, and initialize a new Node.js project. Now that we have initialized a Node.js project we can install modules.
Install axios with the command;
npm install --save axios
Create the file app.js
and astrology.js
in the root of the project. The project structure is;
4. Add API Call
The RapidAPI dashboard can be a useful tool when building an application that makes API calls. Navigate to the API dashboard page or follow this link.
The dashboard has three sections. On the left, select an endpoint.
The middle section provides a definition and displays parameters for the selected endpoint.
Finally, the far-right section has code snippets and example responses for the selected endpoint. Select the Node (Axios) library from the dropdown at the top of the section on the right.
Our setup in the file will be slightly different than the code snippet, but this code is an excellent place to start.
Copy the code below and paste it into astrology.js
const axios = require("axios"); const BASE_URL = `https://astrology-horoscope.p.rapidapi.com` module.exports = { getCompatibility: (yourName, yourBirthday, theirName, theirBirthday) => axios({ method:"POST", url : BASE_URL + `/zodiac_compatibility/result/`, headers: { "content-type":"application/x-www-form-urlencoded", "x-rapidapi-host":"astrology-horoscope.p.rapidapi.com", "x-rapidapi-key": "yourapikey" }, params: { mystic_dob: yourBirthday, mystic_dob2: theirBirthday, mystic_name: yourName, mystic_name2: theirName } }) }
In the above code, we attach an axios API call, named getCompatibility
on to the file export. The function takes four parameters. We determined those parameters from the middle section of the dashboard.
Replace "yourapikey"
with your API-key value from the dashboard. It will be different from mine. It’s important to keep this value secret!
5. Make Asynchronous API Call
Add the code below to app.js
const AstrologyAPI = require('./astrology') const asyncApiCall = async () => { const response = await AstrologyAPI.getCompatibility('Austin', '1987-05-21', 'Taylor', '1989-09-27') console.log(response.data.data.Compatibility.heading) console.log(response.data.data.Compatibility) } asyncApiCall()
At the top of the file, our function imports an object from astrology.js
. An asynchronous function is defined that calls the getCompatibility
function on the imported object. Then, the data is pulled from the response object and logged to the console.
In the terminal enter the command node app.js
.
The response log to the terminal should be similar to;
An Excellent Match { heading: 'An Excellent Match', details: 'Both the Gemini and the Libra are typical air signs and this should make for similar mental characteristics. Both of them have a strong sense of personal freedom, and more importantly, give each other the required space in a relationship. They both desire constant change and share a very active social life. A Gemini and a Libra couple will indeed be extremely popular in the party circuit. However, one thing to be noted is that Libra is not domestic minded, and this might create bitterness especially when the Gemini is in a mood to settle down. Libra however profusely praises his/her lover, and this pleases the Gemini who loves attention. In the bedroom, Libra is sexually active and fulfills all Gemini fantasies. At work, both of them should be good colleagues as well as friends, and both have a strong marketing ability.' }
Notice the first line, “An Excellent Match”, is the value from the response object.
Well done! We have made a successful API call using Node.js. Next, let’s take a look at how this can fit into a larger web application.
Example Application
In a different directory, run the following command to download the example application;
git clone https://github.com/jdretz/rapidapi-node-api-call-example.git
Change directories into the file and run npm install
.
Secure API Key
This application uses the dotenv library to secure the API-key. In utils/astrologyHoroscope.js
you find the same function from the previous section! However, instead of a string value for the "x-rapidapi-key"
header there is process.env.RAPIDAPI_KEY
.
This value is added to the environment by dotenv from the .env
file, but git is told to ignore this file by the .gitignore
file (for more information on ignoring files check out this link). Consequently, this file does not exist in the repository on Github and needs to be created.
Create .env
file
In the root of the project, add the file .env
. Inside the file, add the line;
RAPIDAPI_KEY=yourapikey
The value is now accessible in the environment (process.env
).
How to Call the API?
An understanding of the express library is required to fully comprehend what is going on in src/app.js
. That being said, let’s examine this file and look at the similarities to the previous section.
- Create an API call and import it at the top of the page with the code
const AstrologyHoroscope = require('./utils/astrologyHoroscope')
- Define an asynchronous function on line 41 of
app.js
. - On lines 56-59 call the function and extract data from the response object using dot-notation.
This pattern exists in the small API call example and the larger API call example application.
You can replicate and use that simple pattern to access all kinds of APIs regardless of application. The pattern can even be replicated, with a few small changes, regardless of the library choice. Injecting API calls (for services or data) can be done with precision and speed using Node.js and RapidAPI.
Start the App
For the full application to work, subscribe to the Yoda Translator API. However, please note that the Basic subscription is only free for the first 25/requests a day.
In the root of the project execute the command npm run dev
. Once the development server starts, visit http://localhost:3000 in your browser.
The application is a simple Node.js example that makes external API calls, uses express as a web server, and has a simple user interface.
Conclusion
You have done a lot in this short article and by no means should you stop here! There are many more APIs to explore on RapidAPI and certainly more learning to do with Node.js. Don’t forget about the learning resources from above. If you have questions on specific libraries you can visit npm and search for the specific library to find useful information.
I hope this article shows how external API calls can be sent with Node.js. Furthermore, I hope that it helps you see the relationship between a Node.js application and building out larger API functionality.
If you have comments or questions to the code above please leave a reply for me below!
FAQ
What is the express Node.js framework?
Generally speaking, a framework is a support system for your application. Node provides a set of tools to interface with things your app needs, like the network and the filesystem. A framework extends these capabilities and abstracts away some of the more complicated aspects of development. There are several flavors of the Node framework, and each provides a different programming experience.
Best resources for learning Node.js?
There is an overwhelming amount of material on the internet for learning programming skills. I know how difficult it can be to find tutorials that are worth your time. Therefore, I will list a few of my favorite resources that I have personally used (some that I still use): https://rapidapi.com/blog/how-to-use-an-api-with-node-js/#best-resources-for-learning-nodejs
How To Use An API with Node.js?
1. Sign up for a Free RapidAPI Account 2. Subscribe to an API 3. Set-up Project 4. Add API Call 5. Make Asynchronous API Call
Ricardo says
Why ? I did the same things and copy your code.
Can u help me?
Mike says
The code did not work for me initially but I got it working by adding a “/” to the end of the URL path in this line so it matches the code-snippet in Rapid API:
url : BASE_URL + `/zodiac_compatibility/result/`,
Jarrett Retz says
Thanks for that Mike! We will make that change in the repository.
Daniel says
I’m thinking that maybe the required request body may have changed? When following your code the “response.data.data.Compatibility.heading” returns with “TypeError: Cannot read property ‘Compatibility’ of null”. Looking into it more, when just logging response.data, I get: “data: { status: 0, data: null, message: ‘Gender is Required’ }”. It appears that mystic_gender and mystic_gender2 seem to work with the correct values of “m” or “f”. However, once modifying the params to fit that requirement, I once again get a “null” message. While I now grasp “How to use an API with Node” I’ve become invested in this API a bit and love to see it work! Thanks!