REST API Calls In Express

How To Make REST API Calls In Express Web App

Making API calls is a common thing when it comes to web application development. In this tutorial, you’ll learn how to make REST API calls in express web app.

Creating Express Web App

Let’s get started by creating an express web app. Create a project directory and initialize the node project.

mkdir MakeAPICall
cd MakeAPICall
npm init

Once the project has been initialized, install express framework into the project.

// install express framework
npm install --save express

Create a file called app.js and add the following code:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Welcome to Make REST API Calls In Express!'))

app.listen(port, () => console.log(`App listening on port ${port}!`))

Save the above changes and run the express web app.

// run the app
node app.js

You will have the application running at http://localhost:3000.

Making REST API Calls In Express

Create a new route in express called /getAPIResponse. This route will make a REST API call and return the response as JSON.

app.get('/getAPIResponse', (req, res) => {
    // API code will be here
})

You’ll be making use of the request client to make REST API calls in express. Start by installing request using npm.

// install request module
npm install --save request

Once you have the request module installed, create a file called API_helper.js. This will be wrapper for request module that you are using to make API calls. In future if you need to use any other module, you simple need to modify the API_helper.js wrapper and not every where inside the application.

Require the request module inside the API_helper.js. We’ll be returning a promise from the helper method, so here is how the API_helper.js looks :

const request = require('request')

module.exports = {
    /*
    ** This method returns a promise
    ** which gets resolved or rejected based
    ** on the result from the API
    */
    make_API_call : function(url){
        return new Promise((resolve, reject) => {
            request(url, { json: true }, (err, res, body) => {
              if (err) reject(err)
              resolve(body)
            });
        })
    }
}

As seen in the above code, the make_API_call method returns a promise which gets resolved or rejected based on API response.

Require the above module in the app.js file.

// require API_helper.js
const api_helper = require('./API_helper')

Make an API call to the REST API https://jsonplaceholder.typicode.com/todos/1 using api_helper which returns some dummy JSON data.

Here is the app.js file:

const express = require('express')
const api_helper = require('./API_helper')
const app = express()
const port = 3000

/*
* Route to DEMO the API call to a REST API Endpoint 
* REST URL : https://jsonplaceholder.typicode.com/todos/1
*/
app.get('/getAPIResponse', (req, res) => {
    api_helper.make_API_call('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => {
        res.json(response)
    })
    .catch(error => {
        res.send(error)
    })
})

app.listen(port, () => console.log(`App listening on port ${port}!`))

api_helper returns a promise which when resolved returns a JSON or returns an error when rejected.

Save the above changes and restart the server. Point your browser to http://localhost:3000/getAPIResponse and will have the API response returned in the browser.

Wrapping It Up

In this tutorial, you saw how to make REST API calls in express web app. To make the API calls in express you used the request module. Have you used any other module for making API calls ?

Source code from this tutorial is available on GitHub.

Do let us know your thoughts in the comments below.