JAVASCRIPT

Fetching Data from an API with URL Query Parameters

Discover how to construct and send GET requests to an API, including dynamic query parameters for filtering or specifying data, using JavaScript's fetch API.

async function fetchDataWithQueryParams(baseUrl, params) {
  const query = new URLSearchParams(params).toString();
  const url = `${baseUrl}?${query}`;

  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log('Data with query params:', data);
    return data;
  } catch (error) {
    console.error('Error fetching data with query parameters:', error);
    throw error;
  }
}

// Example usage:
// const apiUrl = 'https://api.example.com/products';
// const queryParams = {
//   category: 'electronics',
//   limit: 10,
//   sort: 'price_asc'
// };
// fetchDataWithQueryParams(apiUrl, queryParams);
How it works: This code shows how to add query parameters to an API request. It uses the `URLSearchParams` constructor to safely encode an object of parameters into a URL-friendly query string. This is crucial for filtering, pagination, or specifying data criteria when making GET requests to a RESTful API.

Need help integrating this into your project?

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

Hire DigitalCodeLabs