The same POST API call in various JavaScript libraries
I was testing an API using Insomnia, a very cool application that lets you perform HTTP requests to REST API or GraphQL API services.
They have a nice button that generates code to replica an API request from the app, where you design all your request data visually.
Internally it uses https://github.com/Kong/httpsnippet which is an HTTP Request snippet generator for many languages & libraries, written in JavaScript. A very cool project.
Anyway, the export had several code snippets. I want to show the same API call in different libraries.
First, here’s the API call description. I make a POST request to the api.randomservice.com website (it’s a random URL I just came up with) to the /dog endpoint.
To this endpoint I send an object with 2 properties:
{
name: 'Roger',
age: 8
}
encoded as JSON.
I also pass a content-type to set the content as application/json and an authorization header to authenticate my request with a Bearer token I was assigned through the API dashboard.
XHR
The first code example is XHR, which we can use in the browser natively, and in Node.js using https://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)
The Fetch API
Then we have the same code using the Fetch API, another API natively available in the browser and in Node.js using https://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)
})
The node HTTPS module
Next up, the native https Node.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()
The request library
Here is the same using the request Node 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
Here is the same using Axios, a popular library for both Node and the browser:
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 all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.