How To Use An API with Node.js (Node.js API Example) (2024)

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.

View the Best Free APIs List

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;

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

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 withdata.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 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

ThePromise 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

New to Node.js

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.

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 RapidAPIto get signed up if you haven’t already!

How To Use An API with Node.js (Node.js API Example) (1)

2. Subscribe to an API

I know that looking up horoscope information does not unleash the full power of APIs. However, RapidAPI has a fun entertainment category that can be good for small applications.

Later we are going to use the Astrology Horoscope API to get compatibility information for two people and then use the Yoda Translator API to read back a sentence from that compatibility report. But for now, we’ll just make an API call to the Astrology Horoscope.

Search for Astrology Horoscope or follow this linkto the subscription page.

How To Use An API with Node.js (Node.js API Example) (2)

Notice I have already subscribed to the Basic plan, therefore I have a link toManage and View Usagethat 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 fileapp.js and astrology.js in the root of the project. The project structure is;

How To Use An API with Node.js (Node.js API Example) (3)

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.

How To Use An API with Node.js (Node.js API Example) (4)

The dashboard has three sections. On the left, select an endpoint.

How To Use An API with Node.js (Node.js API Example) (5)

The middle section provides a definition and displays parameters for the selected endpoint.

How To Use An API with Node.js (Node.js API Example) (6)

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.

How To Use An API with Node.js (Node.js API Example) (7)

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 intoastrology.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 toapp.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 thegetCompatibility function on the imported object. Then, the data is pulled from the response object and logged to the console.

In the terminal enter the commandnode 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.

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 runnpm install.

Secure API Key

This application uses the dotenv library to secure the API-key. Inutils/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 theexpress 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.

  1. Create an API call and import it at the top of the page with the code const AstrologyHoroscope = require('./utils/astrologyHoroscope')
  2. Define an asynchronous function on line 41 of app.js.
  3. 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.

How To Use An API with Node.js (Node.js API Example) (8)

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.

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!

View the Best Free APIs List

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

Related Resources

  • How to use an API with JavaScript
  • How to use an API with React
  • How to use an API with Vue.js

View the Best Free APIs List

3.5/5 - (4 votes)

How To Use An API with Node.js (Node.js API Example) (2024)

FAQs

How do I deploy my Node.js API? ›

Procedure
  1. Select a Node. js application to install. The application must have its dependencies resolved. You will deploy to Liberty a node application compressed TAR archive with the .tgz extension. ...
  2. Make the Node. js application available to the controller. Complete either of the following actions: Put the Node.

How to create a backend API? ›

To create a backend API in Express JS, we need to do the following steps:
  1. Install Node JS and Express JS.
  2. Create a project folder and a server file.
  3. Define the data model and the data array.
  4. Create the routes and the handlers for the API.
  5. Test the API with a tool like Postman.
Nov 20, 2023

How to run Node.js API server? ›

Running a Node. js Server Locally
  1. Step 1: Create a Simple Node. js Server. Initialize a Node. ...
  2. Step 2: Run the Server. Start the Server: In your terminal, run node server. js . ...
  3. Step 3: Stopping the Server. Stop the Server: To stop the server, simply press Ctrl + C in your terminal.
Feb 5, 2024

How to create a rest API server? ›

How to Make a REST API
  1. Identify the Resources – Object Modeling: Begin by pinpointing the core entities or resources for your API. ...
  2. Create Model URIs: Design intuitive URIs for each resource. ...
  3. Determine Resource Representations: Decide on the data format for your resources.
Oct 23, 2023

How to connect API to Node js? ›

Steps to Build API with Node. js
  1. Step 1: Set up the project. Create a new directory for your project. ...
  2. Step 2: Install dependencies. Install the required dependencies by running the following command: npm install express body-parser.
  3. Step 3: Create the server file. ...
  4. Step 4: Run the server.
Apr 11, 2024

How do I write API in node JS? ›

Creating a Basic Node. js API
  1. Create a New Project Folder: Create a new folder for your project using the mkdir command in your command prompt. ...
  2. Navigate to the Project Folder: ...
  3. Create a Node. ...
  4. Edit the "app.js" File: ...
  5. Save the "app. ...
  6. Install Express.js: ...
  7. Run the Node.js File: ...
  8. Access Your API:
Oct 25, 2023

How to consume REST API in Node js? ›

Here are some detailed steps for using Node.js to call REST APIs:
  1. Step 1: Performing API Calls in Node.js with the HTTP Module. ...
  2. Step 1.1: Creating a Node. ...
  3. Step 2: Adapting to Different Scenarios. ...
  4. Step 3: Modifying the Code. ...
  5. Step 4: An Alternative Approach. ...
  6. Step 5: Making POST Requests. ...
  7. Step 1: Create a New Project in Apidog.

How do I send API request to backend? ›

  1. The client sends an API request to the server over the HTTP protocol. This request is in the JSON format.
  2. The server parses this API request, processes the request, and then sends an API response back to the client, which is again in the JSON format.
  3. The client can parse the JSON response object to render it.

How to create API step by step? ›

Follow the steps yourself by signing up for a free OCI account.
  1. In the console, open the navigation menu and click Developer Services. ...
  2. On the APIs page, click Create API Resource and specify its Name. ...
  3. Click Create to create the new API resource.
  4. Write the backend code. ...
  5. Test the backend code. ...
  6. Deploy.

How do I start a Node.js API project? ›

Setting up a Node. js app
  1. Step 1: Install Node. js and NPM. ...
  2. Step 2: Create a new project folder. ...
  3. Step 3: Initialize a new Node. ...
  4. Step 4: Install Express and other dependencies. ...
  5. Step 5: Import necessary modules. ...
  6. Step 6: Define a route that listens to requests. ...
  7. Step 7: Define an endpoint.
May 22, 2023

How to run a Node.js application? ›

The usual way to run a Node.js program is to run the globally available node command (once you install Node.js) and pass the name of the file you want to execute. While running the command, make sure you are in the same directory which contains the app.js file.

Does NPM have an API? ›

This is the API documentation for npm Packages. This API is used by the npm package manager client and is not meant for manual consumption. For instructions on how to upload and install npm packages from the GitLab Package Registry, see the npm package registry documentation.

How do I run an API on a server? ›

The typical steps involved in using an API are:
  1. Look for an API that will meet your needs.
  2. Understand the API terms for using.
  3. Read the API documentation so you can test the API.
  4. Request an API key.
  5. Using the API documentation to make an API request.
  6. Interpret the API response to see if it meets your needs.
Nov 30, 2023

How to use Postman in node JS? ›

Once you have Postman installed, follow these steps to start API testing in Node.js:
  1. Create a Postman Collection. A Postman collection is a group of API requests that you can organize and execute together. ...
  2. Create API Requests. Now, you can add API requests to your collection. ...
  3. Writing Test Scripts.
Nov 29, 2023

How do I create a REST API example? ›

Sign in to the API Gateway console at https://console.aws.amazon.com/apigateway . Do one of the following: To create your first API, for REST API, choose Build. If you've created an API before, choose Create API, and then choose Build for REST API.

Where to deploy node js rest api? ›

The Firebase CLI installed globally ( npm install -g firebase-tools ).
  • Step 1: Initialize Your Node. js Project. ...
  • Step 2: Create Your REST API. ...
  • Step 3: Set Up Firebase. ...
  • Step 4: Prepare Your Application for Firebase Functions. ...
  • Step 5: Write a Firebase Function to Serve Your App. ...
  • Step 6: Deploy Your API to Firebase.
Jan 28, 2024

Where to host node.js API? ›

  • A2 Hosting (www.A2Hosting.com) ...
  • HostGator (www.HostGator.com) ...
  • Heroku (www.Heroku.com) ...
  • Amazon Web Services (AWS.Amazon.com) ...
  • DigitalOcean (www.DigitalOcean.com) ...
  • Glitch (Glitch.com) ...
  • Google Cloud Platform (Cloud.Google.com) ...
  • Microsoft Azure (Azure.Microsoft.com)
Mar 17, 2024

How to deploy Node js API on Windows Server? ›

How to deploy a Node. js application on IIS Windows Server
  1. Add the resource files.
  2. Create the application on the IIS page.
  3. Create the Application Pool.
  4. Enable the required IIS Windows Features.
  5. Launch the application at the end of the installation process.
  6. 6.1 Installing a Node.js web app. ...
  7. Conclusion.

How to deploy rest API on server? ›

Deploy a REST API to a stage
  1. In the APIs navigation pane, choose the API you want to deploy.
  2. In the Resources pane, choose Deploy API.
  3. For Stage, select from the following: To create a new stage, select New stage, and then enter a name in Stage name. ...
  4. Choose Deploy.

Top Articles
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated:

Views: 5703

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.