What is axios.create in JavaScript?

Posted by

I’ll be using repl.it. You can find my repl here.

Before moving forward, let’s set up our environment and get the required API keys.

Create a node project and install axios using the following command

npm i axios

We will be working with the Cat as a Service (CAAS). You can signup for free to get an API Key. If you are interested in learning how to deal with local credentials and javascript, check out this tutorial.

The below code snippet simply makes a couple of requests

const axios = require('axios')
CAT_API_KEY = process.env.CAT_API_KEY

// Request 1
axios.get(
  "https://api.thecatapi.com/v1/images/search",{
    headers: { 'x-api-key' : CAT_API_KEY }
  }
)
.then(
  res=>res
)
.then(
  res=> console.log(res.data)
)
.catch(
  e=>console.log(e)
)

// Request 2
axios.post(
  "https://api.thecatapi.com/v1/votes",
  {"image_id":"7d9", "value": -1},
  { headers: { 'x-api-key' : CAT_API_KEY } }
)
.then(
  res=>res
)
.then(
  res=> console.log(res.data)
)
.catch(
  e=>console.log(e)
)

In both requests, we need to pass a headers object with the API Key and also type the entire API Endpoint. 

axios.create can help us by creating a session-like object. You simply define your headers, your API Base URL, and other configuration once. It will create an instance of axios that can be used to make the requests. You can read more about axios.create here

const CAT_API_CLIENT = axios.create({
  baseURL: 'https://api.thecatapi.com/v1/',
  timeout: 1000,
  headers: { 'x-api-key' : CAT_API_KEY } 
});

// Request 1
CAT_API_CLIENT.get("images/search")
.then(
  res=>res
)
.then(
  res=> console.log(res.data)
)
.catch(
  e=>console.log(e)
)

// Request 2
CAT_API_CLIENT.post("votes",
  {"image_id":"7d9", "value": -1}
)
.then(
  res=>res
)
.then(
  res=> console.log(res.data)
)
.catch(
  e=>console.log(e)
)

We use axios.create to create a client object. For both requests, we no longer need to pass a headers object. You can configure your client by adding more headers or configuring other parameters.

axios.create is particularly helpful when you are working with multiple APIs. You can simply create clients for each API and use those clients.

const CAT_API_CLIENT = axios.create({
  baseURL: 'https://api.thecatapi.com/v1/',
  timeout: 1000,
  headers: { 'x-api-key' : CAT_API_KEY } 
});

const GITHUB_CLIENT = axios.create({
  baseURL: 'https://api.GitHub.com/',
  timeout: 1000,
  headers: {
    'Accept': 'application/vnd.GitHub.v3+json',
    'Authorization': GITHUB_API_KEY
  }
});

const DISCORD_CLIENT = axios.create({
  .....
})

As you can see it using axios.create reduces redundant code and makes it more organized. 

Leave a Reply

Your email address will not be published. Required fields are marked *