DEV Community

Veera Ganapathi
Veera Ganapathi

Posted on

JavaScript Fetch API

Fetch API in JavaScript

  • The Fetch API is a modern interface in JavaScript that allows you to make HTTP requests.
  • It replaces the older XMLHttpRequest method and 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));
Enter fullscreen mode Exit fullscreen mode
  • 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 10

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API</title>
    <style>
        #api{
            display:grid;
            grid-template-columns:1fr 1fr 1fr 1fr;
            gap:20px;
        }
        .card {
            border: 1px solid #ccc;
            padding: 10px;
            margin: 10px;
            width: 200px;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            border-radius: 10px;


        }
        h1{
            text-align:center;
        }
    </style>
</head>
<body>

    <h1>Store Products</h1>
    <div id="api"></div>

    <script>




fetch('https://fakestoreapi.com/products')
.then(res => res.json())
.then(json => {

    let apiData = document.getElementById("api");

    json.forEach(product => {

        apiData.innerHTML +=
        '<div class="card">' +
            '<img src="' + product.image + '" width="100" height="100">' +
            '<p>Title: ' + product.title + '</p>' +
            '<h4>Price: $' + product.price + '</h4>' +
        '</div>';

    });

});

</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)