JSON with Fetch API

The Fetch API is a built-in JavaScript feature that allows a web page to send and receive data from a server without reloading the page. It is the modern way to make HTTP requests in JavaScript. Almost every time a web or mobile app loads fresh data — such as user profiles, product lists, or news articles — the Fetch API (or a similar tool) is used behind the scenes.

JSON is the most common data format used with the Fetch API. The server sends data as JSON, and the browser parses and displays it. This topic covers how to fetch JSON data from a URL, read it, and use it in a real-world way.

How the Fetch API Works — Step by Step

  1. A request is made to a server URL using fetch()
  2. The server responds with data (usually in JSON format)
  3. The response is first received as a Response object
  4. The .json() method is called on the response to parse it into a JavaScript object
  5. The parsed data is then used to update the page or perform operations

Basic Fetch API Syntax

fetch("https://api.example.com/data")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log("Error:", error);
  });

The .then() methods handle the steps in order, and .catch() handles any errors if the request fails.

Fetching JSON from a Public API

Below is a real working example using a free public API (jsonplaceholder.typicode.com) that returns dummy data for learning purposes:

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(function(response) {
    return response.json();
  })
  .then(function(user) {
    console.log("Name: " + user.name);
    console.log("Email: " + user.email);
    console.log("City: " + user.address.city);
  })
  .catch(function(error) {
    console.log("Something went wrong: " + error);
  });

This fetches a single user's data from the server and logs the name, email, and city.

Sample JSON Response from the Server

The API above returns JSON data that looks like this:

{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "city": "Gwenborough",
    "zipcode": "92998-3874"
  },
  "phone": "1-770-736-0988 x56442"
}

Fetching a List (Array) of Data

Most real-world APIs return a list (array) of records. Here is how to fetch a list of posts and display them:

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(function(response) {
    return response.json();
  })
  .then(function(posts) {
    console.log("Total posts received: " + posts.length);

    posts.forEach(function(post) {
      console.log("Title: " + post.title);
    });
  })
  .catch(function(error) {
    console.log("Error: " + error);
  });

Displaying Fetched JSON on a Web Page

Fetched data can be displayed directly in the browser by updating HTML elements:

<!-- HTML -->
<div id="user-info"></div>

<script>
fetch("https://jsonplaceholder.typicode.com/users/2")
  .then(function(response) {
    return response.json();
  })
  .then(function(user) {
    const container = document.getElementById("user-info");
    container.innerHTML = "<h3>" + user.name + "</h3>" +
                          "<p>Email: " + user.email + "</p>" +
                          "<p>Phone: " + user.phone + "</p>";
  })
  .catch(function(error) {
    console.log("Failed to load user data.");
  });
</script>

Using Fetch with async/await (Modern Approach)

The async/await syntax is a cleaner way to write fetch requests. It makes the code read like a simple top-to-bottom script, without chaining multiple .then() calls:

async function getUser() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/users/3");
    const user = await response.json();
    console.log("Name: " + user.name);
    console.log("Website: " + user.website);
  } catch (error) {
    console.log("Error fetching data: " + error);
  }
}

getUser();

Sending JSON Data with POST Request

The Fetch API is also used to send JSON data to a server — for example, when submitting a form. The data is stringified and sent in the request body:

const newPost = {
  title: "Learning JSON",
  body: "JSON is easy and useful.",
  userId: 1
};

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(newPost)
})
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log("Post created with ID: " + data.id);
  })
  .catch(function(error) {
    console.log("Error: " + error);
  });

Key things happening in this POST request:

  • method: "POST" — tells the server this is a data submission
  • headers — tells the server the data is in JSON format
  • body: JSON.stringify(newPost) — converts the JavaScript object to a JSON string for sending

Checking the Response Status

It is good practice to check if the server responded successfully before processing the data:

fetch("https://jsonplaceholder.typicode.com/users/999")
  .then(function(response) {
    if (!response.ok) {
      throw new Error("Server returned status: " + response.status);
    }
    return response.json();
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(error) {
    console.log("Request failed: " + error);
  });

Key Points to Remember

  • The Fetch API is used to request data from a server without reloading the page
  • response.json() parses the server's response into a JavaScript object
  • Always use .catch() or try...catch to handle network errors
  • JSON.stringify() is used when sending JSON data to a server (POST/PUT requests)
  • The async/await syntax makes fetch code easier to read and maintain
  • Always set Content-Type: application/json in headers when sending JSON data

Summary

The Fetch API and JSON are the foundation of modern web communication. Fetching JSON from APIs powers everything from displaying user profiles to loading product catalogues and showing real-time data. Learning to fetch, parse, and display JSON data is one of the most practical and frequently used skills in web development.

Leave a Comment

Your email address will not be published. Required fields are marked *