DEV Community

Cover image for FETCH API IN JAVASCRIPT
G Gokul
G Gokul

Posted on

FETCH API IN JAVASCRIPT

Fetch API in JavaScript:

  • The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests.
  • It provides a cleaner and more flexible way to fetch resources asynchronously.
  • The Fetch API uses Promises, making it easier to work with asynchronous data.

Syntax:

fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

-url: The API endpoint from which data is fetched.
-options (optional): Specifies method, headers, body, etc.
-response.json(): Parses the response as JSON.
-.catch(error): Handles any errors that occur during the request.

How Fetch API Works?

-A request is sent to the specified URL.
-The server processes the request and sends a response.
-The response is converted to JSON (or another format) using .json().
-Errors are handled using .catch() or try-catch blocks.

Task - sample e-commerce api fetch

<style>
        .product-container {
            width: 300px;
            height: 400px;
            border: 2px solid black;
            padding: 10px;
            background-color: aqua;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
        #ecommerce{
            display: flex;
            flex-wrap: wrap;
            gap: 40px;
            justify-content: center;
            align-items: center;
        }
    </style>
Enter fullscreen mode Exit fullscreen mode
<div id="ecommerce">

    </div>

    <script>

        fetch("https://fakestoreapi.com/products")
            .then(res => res.json())
            .then(product)

        function product(products) {
            products.forEach(productslist => {
                const productsContainer = document.createElement("div");
                const img = document.createElement("img");
                const title = document.createElement("h3")
                const price = document.createElement("p")
                const category = document.createElement("p")

                productsContainer.classList.add("product-container")
                img.src = productslist.image
                img.style.width = "200px"
                img.style.height = "200px"
                title.innerText = productslist.title
                price.innerText = productslist.price
                category.innerText = productslist.category

                productsContainer.appendChild(img)
                productsContainer.appendChild(title)
                productsContainer.appendChild(price)
                productsContainer.appendChild(category)

                document.getElementById("ecommerce").appendChild(productsContainer)

            });
        }
    </script>
Enter fullscreen mode Exit fullscreen mode

Output:

fetch

Top comments (0)