How to include query parameters in GET request with Axios

Axios is a promise-based HTTP client that allows you to make HTTP requests in both the browser and Node.js with the same codebase. On the server-side, it uses the native Node.js http module, while on the client (browser), it relies on XMLHttpRequests.

There is a difference between query parameters and path parameters in the context of RESTful APIs:

  • Path parameters are part of the URL path itself, commonly used for unique identifiers, appear as segments within the URL, separated by slashes.
  • Query parameters are appended after the URL path, starting with a ?. They are used to filter, sort, or modify the resources.
GET https://api.example.com/cars/123
GET https://api.example.com/cars?color=blue&brand=ferrari

This tutorial will focus on how to include query parameters in GET requests made with Axios.

Using plain object for params option

This is the recommended and most common approach. You define your query parameters as an object and pass it to the params property of the configuration object in the axios.get() method.

const params = {
  name: 'John Doe',
  age: 30,
  interests: ['coding', 'music']
};

axios.get('https://api.example.com/', { params });

// Resulting URL (example):
// https://api.example.com/?name=John%20Doe&age=30&interests%5B%5D=coding&interests%5B%5D=music

Axios automatically serializes the object into a query string and appends it to the URL. The serialization process involves converting the key-value pairs of the object into a URL-encoded format.

Using a plain object directly translates your data structure into query parameters, making the code intuitive and easier to understand. Adding or removing parameters simply involves modifying the object, keeping the code organized and adaptable.

You have less control over the exact formatting of the query string, such as array handling or custom separators. Special characters in parameter values might require manual encoding if not handled automatically by Axios.

Using a plain object as params in GET requests with Axios is a good choice for simplicity, readability, and flexibility, especially for basic use cases. However, if you need fine-grained control over query string formatting or work with complex data structures, URLSearchParams might be a better fit.

Using URLSearchParams for params option

When you need more control over query string formatting (array handling, separators, encoding), you can also create an instance of URLSearchParams class and pass it as the params option.

import axios from 'axios';

const params = new URLSearchParams();
params.append('search', 'javascript'); // Automatically encodes spaces
params.append('filter', ['framework', 'library']); // Serializes array correctly
params.append('sort', 'stars', { separator: ',' }); // Custom separator for multiple values

axios.get('https://api.example.com/', { params })
  .then(/* ... */)
  .catch(/* ... */

URLSearchParams is a built-in JavaScript object specifically designed to create and manage query parameters for URLs. It offers several advantages over using plain objects as params in GET requests:

  • It automatically serializes arrays using the specified array bracket notation (e.g., key[]=value1&key[]=value2), ensuring correct interpretation by servers.
  • It handles URL encoding automatically, preventing issues with special characters (spaces, periods, hyphens, underscores, tildes, exclamation marks, asterisk, parentheses, apostrophes, plus signs, commas, forward slashes, backslashes, percent signs, number signs, at signs, equal signs, question marks, ampersands).
  • No reliance on implicit object property names, preventing naming conflicts that can occur with plain objects.

Customizing Serialization

Axios automatically serializes query parameters, but you can customize it further using the paramsSerializer option:

const params = {
  param1: "value1",
  param2: "value2",
  // Add more parameters as needed
};

axios
  .get("https://api.example.com/data", {
    params,
    paramsSerializer: function customSerializer(params) {
      // Customize serialization logic here
      return Object.entries(params)
        .map(([key, value]) => `${key}=${value}`)
        .join("&");
    },
  })
  .then(/* ... */)
  .catch(/* ... */);

While paramsSerializer in Axios offers customization for serialization, you generally don’t need to use it for most GET requests as Axios handles basic cases well.

If you need to format your data in a way that doesn’t match the default Axios handling, paramsSerializer provides control. For example:

  • Formatting dates in a specific format
  • Serializing nested objects in a custom way
  • Handling arrays with non-standard separators