GET Request Query Params with Axios

In this blog, we will learn how to use query params with the Axios Get request. Generally, query parameters define a set of parameters which are present at the end of a URL. Using query parameters, we can fetch the records from the API based on the IDs or the information sent to the backend API using the query parameters. We will be exploring the Axios Get request api call in detail with this tutorial.

Let’s see an example for better understanding.

GET API Call without Parameter

Note: Below code is suitable for fetching multiple records, but for fetching the specific records based on the ID refer to the api call with the ID parameter. (Reference shared in the next section of this article).

Code

Example 1:
const axios = require('axios');
axios.get(`https://jsonplaceholder.typicode.com/posts/1`)
.then(res => console.log(res.data))

Example 2:
const axios = require('axios');
const res = await axios.get('https://httpbin.org/get?answer=12');
res.data.args; // { answer: 12 }

Output

Output of Example 1:

{
    userId: 1,
    id: 1,
    title: 'Test Record from the Get API Call',
    body: 'I am the body of the test record\n' +
      'Last line of the record.'
  }

About (Pros & Cons of the above request)

Here we have used a free API to make a get request to backend. To complete this action with Axios we have to call axios.get() method provided by the library. Here, with the above api call we will get the data based on the provided API URL. In the demo we have called the API with an ID, but generally we don’t add a static value like above in the URL, but if we don’t add the ID in the URL then we will get a lot of data from the API by using an Axios.get() request. Our aim is to access the data using an ID number or any other unique identification for filtering the records. This process is pretty simple in Axios. And the process is called query params. The code below explains this more clearly

GET API Call with Parameter (Recommended)

Code

Example 1:
const axios = require('axios');
axios.get(`https://jsonplaceholder.typicode.com/posts`,{
    params: {
      id: 1
    }
  })
.then(res => console.log(res.data))

Example 2:
const axios = require('axios');
// Equivalent to `axios.get('https://httpbin.org/get?answer=42')`
const res = await axios.get('https://httpbin.org/get', { params: { answer: 22 } });
res.data.args; // { answer: 22 }

Output (Same as above)

Output of Example 1:

{
    userId: 1,
    id: 1,
    title: 'Test Record from the Get API Call',
    body: 'I am the body of the test record\n' +
      'Last line of the record.'
 }

Here, we have specified the ID number and we get the information of the user with the specified id number as 1. In this way we showed that querying data is so useful in creating applications and you can always follow back to this article to make a GET request Query params with Axios for fetching your data from the backend API.

BONUS

Get Request Using Built-in URLSearchParams

Code (Set Parameter using JavaScript’s built-in URLSearchParams class)

const params = new URLSearchParams([['answer', 42]]);

const res = await axios.get('https://httpbin.org/get', { params });
res.data.args; // { answer: 42 }

Customizing Serialization

Code 1

Axios automatically serializes the built-in custom JSON serialization.


const moment = require('moment');

const params = {
  answer: { toJSON: () => 42 },
  time: moment('2016-06-01')
};

const res = await axios.get('https://httpbin.org/get', { params });
res.data.args; // { answer: 42, time: "\"2016-06-01T04:00:00.000Z\"" }

Code 2

Axios also supports a paramsSerializer with which we can easily overwrite the Axios function to serialize.


const params = { answer: 42 };

const res = await axios.get('https://httpbin.org/get', {
  params,
  paramsSerializer: function paramsSerializer(params) {
    // "Hide" the `answer` param
    return Object.entries(Object.assign({}, params,  { answer: 'HIDDEN' })).
      map(([key, value]) => `${key}=${value}`).
      join('&');
  }
});
res.data.args; // { answer: 'HIDDEN' }

Hope the article was informative, Comment below your doubts and suggestions,

1 thought on “GET Request Query Params with Axios”

Leave a Comment