Skip to main content

Making an API call in NodeJS

There are many ways available to send HTTP request or make a REST API call during acceptance testing:

1. HTTP - The standard library

  • default HTTP module in the standard Node.js library.
  • No need to install any external dependency.
  • It is NOT very user-friendly compared to other solutions.
  • It does not parse the response data manually.
  • It does not support HTTPS by default, so you need to require the https module instead if required.

2. Request - Simplified HTTP client

  • An easy to use library that deals with HTTP requests
  • For promise handling, use Bluebird or switch to request-promise library

3. Codecept REST API Helper

  • This helper use unirest to perform requests.
  • Provides easy to understand DSL

4. Unirest

  • Lightweight HTTP Request Client library
  • Provides a cookie jar to store multiple cookies

5. Axios

  • This is a promise based HTTP client for the browser and node.js

  • Make XMLHttpRequests from the browser

  • Make http requests from node.js

  • Supports the Promise API

  • Intercept request and response

  • Transform request and response data

  • Cancel requests

  • Automatic transforms for JSON data

  • Client-side support for protecting against XSRF

  • The request contains the following information:

    data: ,status, statusText, headers, config (the config that was provided to axios with request), request.

Resources:

axios cheat sheet

Getting started with axios tutorial

6. node-fetch

  • A light-weight module that brings window.fetch to node.js
  • Stay consistent with window.fetch API.
  • Use native promise, but allow substituting it with other popular promise libraries like Bluebird
  • Use native Node streams for body, on both request and response.
  • Useful extensions such as timeout, redirect limit, response size limit, explicit errors for troubleshooting.

7. request-promise

  • Simplified HTTP request client 'request' with Promise support. Powered by Bluebird.
  • request-promise wraps around request so everything that works with request also works with request-promise

8. SuperAgent

  • Makes AJAX requests from the browser
  • Make http requests from node.js
  • Provides a function query() to add parameters to the request.
  • It parses the JSON response automatically.


References:

https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

https://codeburst.io/how-to-make-an-http-request-in-nodejs-http-mechanism-libraries-f25ec990d307

Why use Promise Libraries while Node.js has added native support for promises?

Learning Promises: https://scotch.io/tutorials/javascript-promises-for-dummies