Making HTTP Requests in JavaScript with Fetch API

2 min read .

The Fetch API is a powerful tool in JavaScript for making HTTP requests, allowing you to interact with servers, APIs, and other web services. In this guide, we’ll explore how to use the Fetch API to perform various CRUD (Create, Read, Update, Delete) operations using examples from the DummyJSON API.

1. Introduction to the Fetch API

The Fetch API provides a modern, promise-based way to make HTTP requests in JavaScript. It’s an improvement over the older XMLHttpRequest object and offers a cleaner, more intuitive syntax.

2. Fetching All Products

To get a list of all products from the DummyJSON API, you can use a simple GET request. Here’s how:

fetch('https://dummyjson.com/products')
  .then(res => res.json())
  .then(console.log);

This code sends a GET request to the /products endpoint, retrieves the response in JSON format, and logs it to the console.

3. Fetching a Single Product by ID

If you want to fetch a specific product by its ID, you can do so by including the product ID in the URL:

fetch('https://dummyjson.com/products/1')
  .then(res => res.json())
  .then(console.log);

This example fetches the product with ID 1 and logs its details to the console.

4. Searching for Products

You can also search for products by query. For instance, to search for products related to “phone,” use the following code:

fetch('https://dummyjson.com/products/search?q=phone')
  .then(res => res.json())
  .then(console.log);

This will return a list of products that match the search query “phone.”

5. Adding a New Product

To add a new product to the DummyJSON database, you need to send a POST request with the product data in the request body:

fetch('https://dummyjson.com/products/add', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: 'BMW Pencil',
    /* other product data */
  })
})
  .then(res => res.json())
  .then(console.log);

In this example, a new product titled “BMW Pencil” is added to the database. The server’s response, including the newly created product details, is logged to the console.

6. Updating a Product

To update an existing product, such as changing its title, you can use a PUT or PATCH request:

fetch('https://dummyjson.com/products/1', {
  method: 'PUT', /* or PATCH */
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    title: 'iPhone Galaxy +1'
  })
})
  .then(res => res.json())
  .then(console.log);

This code updates the title of the product with ID 1 to “iPhone Galaxy +1.”

7. Deleting a Product

Finally, to delete a product from the database, you can send a DELETE request to the product’s specific endpoint:

fetch('https://dummyjson.com/products/1', {
  method: 'DELETE',
})
  .then(res => res.json())
  .then(console.log);

This request deletes the product with ID 1, and the server’s response is logged to the console, typically confirming the deletion.

8. Best Practices for Using the Fetch API

  • Handle Errors Gracefully: Always include error handling when making HTTP requests to manage network issues or invalid responses. You can use .catch() to handle errors.

  • Use Async/Await for Better Readability: While promises are great, using async/await can make your code more readable, especially when handling multiple asynchronous operations.

    Example:

    async function fetchProducts() {
      try {
        const res = await fetch('https://dummyjson.com/products');
        const data = await res.json();
        console.log(data);
      } catch (error) {
        console.error('Error fetching products:', error);
      }
    }
    
    fetchProducts();
  • Secure Your API Requests: Ensure that sensitive information is handled securely, especially when dealing with authentication and user data.

Conclusion

The Fetch API is a versatile tool for making HTTP requests in JavaScript, allowing you to easily interact with APIs and perform CRUD operations. Whether you’re fetching data, updating resources, or deleting entries, understanding how to use the Fetch API effectively is crucial for modern web development.

See Also

chevron-up