Tehnologii Web/2022-2023/Laborator 4

In this laboratory, we will fetch data from an external server, and we will create a page containing products.

  • Using fetch - we will retrieve data from a REST API, from a GET method .
  • Using fetch - we will POST new entries.

We will use Javascript in the following steps, ES6 (ECMA Script 2015) is at this time - a browser standard, but older browsers might only support older Javascript.

If your environment from the first lab with Parcel is being set correctly - Parcel should be doing this conversion automatically.

Laboratory Steps

edit
 
Lab assignment: fetch JSON API and display the products.

Step 1

edit

Find a dummy JSON-api service. For instance: DummyJSON would be an option.

Visit: https://dummyjson.com/products/1

The resulted page would look like this:

{
    "id": 1,
    "title": "iPhone 9",
    "description": "An apple mobile which is nothing like apple",
    "price":549,
    "discountPercentage":12.96,
    "rating":4.69,
    "stock":94,
    "brand":"Apple",
    "category":"smartphones",
    "thumbnail":"https://dummyjson.com/image/i/products/1/thumbnail.jpg",
    "images":[
        "https://dummyjson.com/image/i/products/1/1.jpg",
        "https://dummyjson.com/image/i/products/1/2.jpg",
        "https://dummyjson.com/image/i/products/1/3.jpg",
        "https://dummyjson.com/image/i/products/1/4.jpg",
        "https://dummyjson.com/image/i/products/1/thumbnail.jpg"
    ]
}

By default, our browsers would call the GET method.

Step 2

edit

Implement the static HTML and CSS (no JS) in order to replicate the user interface for this assignment.

You should have a container and multiple products, your HTML hierarchy should look like this:

<div id="container">
    <div class="product">
        <img src="...your image URL" />
        <span class="title">IPhone 9</span>
        <span class="description">An apple mobile which is nothing like apple.</span>
        <span class="price">499$</span>
    </div>
    
    <div class="product">
        <img src="...your image URL" />
        <span class="title">Universal Phone</span>
        <span class="description">Revolutionary smartphone with keyboard.</span>
        <span class="price">199$</span>
    </div>
</div>

Step 3

edit

Retrieve the container (using Javascript).

const container = document.getElementById("container");

Step 4

edit

Add product entries dynamically using Javascript.

First, we create a helper function that will return an HTML string - representing a product HTML template.

Please note Javascript template literals.[1]

function renderProduct(title, description, price, imageURL) {
  return `<div class="product">
            <img src="${imageURL}" />
            <span class="title">${title}</span>
            <span class="description">${description}</span>
            <span class="price">${price}</span>
         </div>
    `;
}

Next, we will add the resulted HTML string to a newly created child.

var product = document.createElement('div');
product.innerHTML = renderProduct('iPhone 9', 'description', 399, '...your image URL');
// now let's add the product in the DOM hierarchy
container.appendChild(product);

Step 5

edit

By now, you should have at least 2 products (added from static HTML code), and a product created from your Javascript code.

Visit: https://dummyjson.com/products in your browser to see the expected JSON data.

Step 6

edit

Call the fetch function and open the browser inspector console, you should see your JSON data.

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

Step 7        

edit

Finally, we iterate through the products and we add them in the DOM dynamically.

fetch('https://dummyjson.com/products')
    .then(res => res.json())
    .then(json => {
        for (const product of json.products) {
            let productElement = document.createElement('div');
            productElement.innerHTML = renderProduct(
                product.title, 
                product.description,
                product.price,
                product.thumbnail
            );
            container.appendChild(productElement);
        }
    })

Your assignment

edit

Take input from user (navbar) and using fetch - call add products endpoint .

POST /products/add

Your fetch call should look like this:

fetch('https://dummyjson.com/products/add', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        title: '...your title',
        description: '...your description',
        price: 123 // your price
    })
}).then(res => res.json())
  .then(json => {
      console.log(json)
   });

Note: you might experience CORS problems, Parcel settings should allow bypass this by default.

Bonus

edit

Implement a real-time search (will search both partially the title and the description).