How to pass URL parameters in Axios

How to pass URL parameters in Axios

When you’re crafting HTTP requests in JavaScript, especially with libraries like Axios, the params object is your go-to for appending URL parameters without manually concatenating strings. Instead of wrestling with ? and &, you just pack your key-value pairs into params, and the library handles the rest.

Here’s the essence: if you want to send something like ?user=alice&role=admin in a GET request, just do this:

axios.get('/api/users', {
  params: {
    user: 'alice',
    role: 'admin'
  }
})
.then(response => {
  console.log(response.data);
});

Behind the scenes, Axios converts that params object into a proper query string, encoding values as needed. You don’t have to worry about escaping characters or forgetting the ampersand.

This approach is much cleaner than string-building URLs by hand and less error-prone. It also plays nicely with dynamic parameters, where values might come from variables or user input. For example:

const searchTerm = 'network+security';
const pageNumber = 2;

axios.get('/search', {
  params: {
    q: searchTerm,
    page: pageNumber
  }
})
.then(({ data }) => {
  console.log(data.results);
});

Notice that even the plus sign in network+security gets correctly URL-encoded under the hood, sparing you from subtle bugs.

One subtlety worth calling out: if you assign null or undefined to a parameter, Axios will skip it rather than sending param=null or param=undefined. This behavior keeps your URLs tidy and avoids confusion on the server side.

For example:

axios.get('/api/items', {
  params: {
    category: 'books',
    filter: undefined,  // ignored
    sort: null          // ignored
  }
});

Results in a URL like /api/items?category=books, no extraneous parameters.

Finally, it’s worth mentioning that you can mix params with other request options seamlessly – headers, data payloads for POST, timeouts – without any collisions. This modular approach lets you build requests that are both readable and maintainable.

Handling complex query strings with parameter serialization

When dealing with complex query strings, especially those that require nested objects or arrays, serialization becomes crucial. Axios simplifies this with its ability to handle these scenarios gracefully. By default, Axios uses the qs library for parameter serialization, which allows you to structure your parameters in a way that makes sense for the server.

For instance, if you want to send a query string that looks like ?filters[category]=books&filters[price][min]=10&filters[price][max]=50, you can structure your params object like this:

axios.get('/api/products', {
  params: {
    filters: {
      category: 'books',
      price: {
        min: 10,
        max: 50
      }
    }
  }
})
.then(response => {
  console.log(response.data);
});

This nested structure is automatically converted into the appropriate query string format by Axios. It’s clean, readable, and avoids the headache of manually constructing complex query strings.

Additionally, if your parameters include arrays, Axios handles them freely as well. Consider a scenario where you need to filter by multiple tags:

const tags = ['javascript', 'programming', 'web'];

axios.get('/api/articles', {
  params: {
    tags: tags
  }
})
.then(({ data }) => {
  console.log(data.articles);
});

This will produce a query string like ?tags=javascript&tags=programming&tags=web, which is exactly what many APIs expect. The automatic handling of arrays ensures that you don’t have to worry about the format.

For even more control over serialization, you can customize Axios’s behavior by providing a paramsSerializer function. This is useful when you need a specific format that the default serialization does not support. Here’s how you might implement a custom serializer:

const customParamsSerializer = params => {
  return Object.keys(params)
    .map(key => ${encodeURIComponent(key)}=${encodeURIComponent(params[key])})
    .join('&');
};

axios.get('/api/items', {
  params: {
    search: 'laptop',
    sort: 'asc'
  },
  paramsSerializer: customParamsSerializer
})
.then(response => {
  console.log(response.data);
});

This flexibility allows you to align your requests with the API’s expectations while using Axios’s powerful features.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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