JAVASCRIPT

Build Dynamic Query Parameters for GET Requests

Learn to programmatically construct URL query strings from an object, simplifying API requests with varying parameters in JavaScript for frontend or Node.js.

function buildQueryParams(baseUrl, params) {
  const queryString = Object.keys(params)
    .map(key => {
      const value = params[key];
      if (value !== null && value !== undefined && value !== '') {
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      }
      return '';
    })
    .filter(param => param !== '')
    .join('&');

  return queryString ? `${baseUrl}?${queryString}` : baseUrl;
}

// Example Usage:
const apiUrl = 'https://api.example.com/items';
const filters = {
  category: 'electronics',
  minPrice: 100,
  sortBy: 'price',
  page: 2,
  search: 'laptop',
  emptyParam: null, // Will be ignored
  undefinedParam: undefined, // Will be ignored
  anotherEmpty: '' // Will be ignored
};

const finalUrl = buildQueryParams(apiUrl, filters);
console.log(finalUrl);
// Expected: https://api.example.com/items?category=electronics&minPrice=100&sortBy=price&page=2&search=laptop

// To make an actual fetch request:
/*
fetch(finalUrl)
  .then(response => response.json())
  .then(data => console.log('Fetched data:', data))
  .catch(error => console.error('Error fetching data:', error));
*/
How it works: This snippet provides a utility function to construct a URL with dynamic query parameters. It takes a base URL and an object of parameters, then iterates through the object, encodes each key-value pair, and appends them to the URL. It intelligently ignores `null`, `undefined`, or empty string values, preventing messy URLs and streamlining API request construction.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs