Same POST API call in different JavaScript libraries
When testing APIs, it’s common to use tools like Insomnia to perform HTTP requests to REST API or GraphQL API services. In this blog, I want to showcase the same API call implemented in different JavaScript libraries.
API Call Description
Let’s consider an example API call - a POST request to the api.randomservice.com
website’s /dog
endpoint. The request body includes an object with two properties: name
and age
, encoded as JSON. Additionally, the request needs a content-type
header set to application/json
and an authorization
header with a Bearer token for authentication.
Now, let’s explore how this API call can be implemented in various JavaScript libraries.
XHR
The first library we’ll cover is XHR. This library can be used in the browser natively or in Node.js with the help of the xmlhttprequest
package. Here’s an example of the API call using XHR:
1 | const data = JSON.stringify({ |
Fetch API
The Fetch API is another native JavaScript library that can be used in the browser and in Node.js with the help of the node-fetch
package. Here’s the API call implemented using the Fetch API:
1 | fetch('https://api.randomservice.com/dog', { |
node HTTPS module
The native https
module in Node.js can also be used to make the API call. Here’s an example:
1 | const https = require('https'); |
request library
The request
library is another popular choice for making API calls in Node.js. Here’s how the API call can be implemented using the request
library:
1 | const request = require('request'); |
Axios
Finally, let’s explore how the API call can be made using the popular Axios library, which works in both Node.js and the browser:
1 | const axios = require('axios'); |
tags: [“API”, “JavaScript libraries”, “XHR”, “Fetch API”, “node HTTPS module”, “request library”, “Axios”]