DEV Community

Cover image for Json and API fetch in js
Keerthana M
Keerthana M

Posted on

Json and API fetch in js

JSON:

  • JSON means JavaScript Object Notation.
  • JSON is a Text Format for storing and exchanging data.
  • JSON is a array of object.

JSON Structure

  • JSON data is composed of objects and arrays:

Objects:

  • Enclosed in curly braces {}, containing name/value pairs. Each name (key) must be a string in double quotes, followed by a colon and a value.

Example:
{
"firstName": "John",
"lastName": "Doe",
"age": 30
}

Arrays:

  • Enclosed in square brackets [], containing a list of values, which can be objects, strings, numbers, or other arrays.

Example:
{
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
}

API :

  • API means Application Programming Interface.
  • It build the communication between frontend and backend.

Fetch:

  • Fetch is a function we give the parameter as a data URL which means (JSON file)
  • This function return promise .
  • If the promise resolve means it will go to the .then function if it is resolve means again it will go to the the next .then function .

  • If the promise does not resolve means it will go to the .catch function

const api=fetch('https://fakestoreapi.com/products/1')
api.then(()=>console.log("success"))
   .cache(()=>console.log("rejected"))
Enter fullscreen mode Exit fullscreen mode

Output

success

when the .cache takes action:

  • when the .then is fails to return success. Then the cache is taken place.

  • The .cache return as rejected instead of success.

program:

const api=fetch('http://fakestoreapi.com/products/1')
api.then(()=>console.log("success"))
   .cache(()=>console.log("rejected"))
Enter fullscreen mode Exit fullscreen mode

output:

rejected

  • due to the mistake of https, the was an http and it doesnot reach the .then so .cache returns the rejected.

Fetch API in JS:

  • 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));

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 - 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>
<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:

Top comments (0)