# The same POST API call in various JavaScript libraries

> See the same POST API request written five ways in JavaScript, with XHR, the Fetch API, the Node https module, the request library, and Axios side by side.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-04-08 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/how-to-post-api-javascript/

I was testing an API using [Insomnia](https://insomnia.rest/), a very cool application that lets you perform HTTP requests to REST API or [GraphQL](https://flaviocopes.com/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](https://flaviocopes.com/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:

```js
{
  name: 'Roger',
  age: 8
}
```

encoded as [JSON](https://flaviocopes.com/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](https://flaviocopes.com/xhr/), which we can use in the browser natively, and in [Node.js](https://flaviocopes.com/nodejs/) using <https://www.npmjs.com/package/xmlhttprequest>: 

```js
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](https://flaviocopes.com/fetch-api/), another API natively available in the browser and in Node.js using <https://www.npmjs.com/package/node-fetch>:

```js
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:

```js
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`](https://www.npmjs.com/package/request) Node library:

```js
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](https://flaviocopes.com/axios/), a popular library for both Node and the browser:

```js
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)
})
```
