Using an API with Query Parameters

By using Query parameters with API requests, you can include additional information with API requests to get a specific set of data. Here is a simple example of using query parameters with API requests:

// API endpoint URL
const apiUrl = 'https://api.example.com/books';

// Parameter for filtering by category
const categoryParameter = 'fiction';

// Construct the URL with query parameters
const urlWithParameters = `${apiUrl}?category=${categoryParameter}`;

// Make the API request using fetch()
fetch(urlWithParameters)
  .then(response => {
    // Check if the response is successful (status code 200-299)
    if (response.ok) {
      // Parse the JSON response
      return response.json();
    } else {
      // If response is not successful, throw an error
      throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }
  })
  .then(data => {
    // Process the fetched data
    console.log(data);
  })
  .catch(error => {
    // Handle any errors that occur during the fetch operation
    console.error(error);
  });

Explanation:

In the above example, we're creating an API request to get all the fiction book names. Let's understand how the code works:

  1. API Endpoint URL: The const apiUrl constant holds the base URL of the API endpoint.

  2. Query Parameter: The categoryParameter constant specifies the category parameter value used for filtering data.

  3. Constructing URL: The URL with query parameters is constructed using string interpolation to include the base URL (apiUrl) and the category parameter (categoryParameter).

  4. Making API Request: The fetch() function is used to make the API request to the constructed URL (urlWithParameters).

  5. Handling Response: In the .then() block, the response is checked for success (status code in the range 200-299). If successful, the JSON response is parsed using response.json(). If not successful, an error is thrown with details of the status code and status text.

  6. Processing Data: After successfully parsing the JSON response, the fetched data is processed as needed. In this example, it is logged to the console.

  7. Error Handling: The .catch() block catches any errors that occur during the fetch operation and logs them to the console for debugging purposes.