Saturday, November 4, 2023

API Calls In NodeJS 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
})

Install request using npm: 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 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.