Invoke REST APIs In Express JS

Introduction

This article will explain the steps involved in invoking APIs from the Express JS framework. The code below will assume the REST APIs are already developed and available for consumption.

Create a simple Express application

Use the below lines of code to create an Express app.

const express =require(‘express’);
const app = express();
app.get('/', function (req, res) {
  res.send('Hello World!')
})
app.listen(3000);

The app will respond with a Hello World message when a GET request is initiated (http://localhost:3000)

Invoke REST APIs

GET method,

const request = require('request');
//define http request implementation in a separate file to handle request input and output //parameters
async function getEmployee(req, res) {
    let body = req.body;
    let options = {
        hostname: ‘http: //sampleservice.com/’,
            path: '/api/Employee'
        method: ‘GET’
    }
    let result = await request(options);
    res.send(); // or return specific parameter value in JSON format 
}

Invoke POST method,

async function UpdateEmployee(req, res) {
    let body = req.body;
    let details = {
        name: body.name,
        id: body.id,
        title: body.title
    };
    let options = {
        hostname: http: //sampleservice.com/,
            path: '/api/employee?' + new params({
                name,
                id,
                title
            }),
        method: 'POST'
    }
    let result = await request(options, details);
    res.json({
        body.id,
        body.name,
        body.title
    });
}

Conclusion

API calls also can be made using fetch command with minimal code, it requires at least Node.js 12.20 version.