Fetch API Demo

What is Fetch API?

JavaScript Fetch API is a web Application Programming Interface(API) which allows to make HTTP request to the web server from web browser. In JavaScript, Fetch API is introduced in ES6 version.

The window object contains Fetch API by default and provides fetch() method that can be used to access resources asynchronously across the web.

Syntax
[window.]fetch(URL, [options])
Parameters:
  • URL − It is an API endpoint where you need to make a request.
  • options − It is an optional parameter. It is an object containing the method, headers, etc., as a key.
Return:
  • It returns the promise, which you can solve using the 'then...catch' block or asynchronously.
fetch() with 'then...catch'
fetch(URL)
.then(response => response.json())
.then(data => {
  // Handle data
}).catch(err => {
  // Handle error
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Fashion Store</title>
  <link rel="stylesheet" href="index.css">
  <script src="index.js"></script>
</head>
<body style="margin: 0px;padding: 0px;">
  <h2 style="color: white;background-color: black;text-align: center;margin: 0px;padding: 0px;">E-COMMERCE</h2>
  <div class="products" id="products" align="center"></div>
</body>
</html>

index.css
.products{
  display: flexbox;
}

.card{
  display: inline-block;
  margin: 5px;
  padding: 5px;
  width: 300px;
  border-style: solid;
  border-radius: 10px;
  border-color: white;
  box-shadow: 3px 3px 5px grey;
}

.itemtitle{
  width: 200px;
}
.itembtn{
  border-style: solid;
  border-radius: 10px;
  padding: 10px;
  border-color: orangered;
  background-color: orangered;
  color: white;
  font-weight: bold;
}

index.js
fetch("https://fakestoreapi.com/products")
.then(response => response.json())
.then(data => {
  data.forEach(item => {
    let card = document.createElement('div')
    card.setAttribute("class","card")
    card.setAttribute("align","center")
    let itemtitle = document.createElement('div')
    itemtitle.setAttribute("class","itemtitle")
    itemtitle.innerText = item.title
    let itemimage = document.createElement('img')
    itemimage.setAttribute("src",item.image)
    itemimage.setAttribute("alt","")
    itemimage.setAttribute("width","250px")
    itemimage.setAttribute("height","150px")
    let itemprice = document.createElement('div')
    itemprice.innerText = "Price: "+item.price
    let itembtn = document.createElement('button')
    itembtn.setAttribute("type","button")
    itembtn.setAttribute("class","itembtn")
    itembtn.innerText = "Add to cart"
    card.append(itemtitle, itemimage, itemprice, itembtn)
    document.getElementById('products').appendChild(card)
  })
}).catch(err =>{
  console.log("Error in fetch data")
})
Output

E-COMMERCE