The same POST API call in various JavaScript libraries

I am using test APIinsomnia, This is a very cool application that allows you to perform HTTP requests to REST API or GraphQL API services.

They have a beautiful button that can generate code to replicate the API request from the application, where you can visually design all the request data.

Used internallyhttps://github.com/Kong/httpsnippetThis is an HTTP request code snippet generator written in multiple languages and libraries using JavaScript. A very cool project.

In any case, there are several code snippets for export. I want to display the same API call in different libraries.

First of all, here is the API call description. I make a POST requestapi.randomservice.comWebsite (this is the random URL I just came up with)/dogEndpoint.

I send an object with 2 properties to the endpoint:

{
  name: 'Roger',
  age: 8
}

Encoded as JSON.

I also passedcontent-typeSet content toapplication/jsonwithauthorizationHeader to authenticate my request using the Bearer token assigned through the API dashboard.

XHR

The first code example isXHR, We can use it in the browser or in Node.jshttps://www.npmjs.com/package/xmlhttprequest:

const data = JSON.stringify({
  name: 'Roger',
  age: 8
})

const xhr = new XMLHttpRequest() xhr.withCredentials = true

xhr.addEventListener(‘readystatechange’, function() { if (this.readyState === this.DONE) { console.log(this.responseText) } })

xhr.open(‘POST’, https://api.randomservice.com/dog) xhr.setRequestHeader(‘content-type’, ‘application/json’) xhr.setRequestHeader(‘authorization’, ‘Bearer 123abc456def’)

xhr.send(data)

Extract API

Then we useExtract API, This is another API available natively in the browser and Node.js, usehttps://www.npmjs.com/package/node-fetch:

fetch('https://api.randomservice.com/dog', {
  method: 'POST',
  headers: {
    'content-type': 'application/json',
    authorization: 'Bearer 123abc456def'
  },
  body: {
    name: 'Roger',
    age: 8
  }
})
  .then(response => {
    console.log(response)
  })
  .catch(err => {
    console.log(err)
  })

Node HTTPS module

Next, the localshttpsNode.js module:

const http = require('https')

const options = { method: ‘POST’, hostname: api.randomservice.com, port: null, path: ‘/dog’, headers: { ‘content-type’: ‘application/json’, authorization: ‘Bearer 123abc456def’, ‘content-length’: ‘32’ } }

const req = http.request(options, res => { const chunks = []

res.on(‘data’, chunk => { chunks.push(chunk) })

res.on(‘end’, () => { const body = Buffer.concat(chunks) console.log(body.toString()) }) })

req.write(JSON.stringify({ name: ‘Roger’, age: 8 })) req.end()

Thisrequestlibrary

This is the same as usingrequestNode library:

const request = require('request')

const options = { method: ‘POST’, url: https://api.randomservice.com/dog, headers: { ‘content-type’: ‘application/json’, authorization: ‘Bearer 123abc456def’ }, body: { name: ‘Roger’, age: 8 }, json: true }

request(options, (error, response, body) => { if (error) throw new Error(error)

console.log(body) })

Axios

This is the same useAxios, This is a popular library for Node and browsers:

const axios = require('axios')

axios.post(https://api.randomservice.com/dog, { name: ‘Roger’, age: 8 }, { headers: { ‘content-type’: ‘application/json’, authorization: ‘Bearer 123abc456def’ } ) .then((res) => { console.log(res.data) }) .catch((error) => { console.error(error) })

Download mine for freeJavaScript beginner's manual


More js tutorials: