Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - Why Fetching Data Matters
  • - What Is JSON?
  • - What Is an API?
  • - Fetching Data Using fetch()
  • - Async/Await Syntax
  • - Manipulating Fetched Data
  • - Error Handling in Depth
  • - Mini Challenge

. Working with JSON and Fetching Data from APIs

Level: Duration: 35m

Why Fetching Data Matters

Modern web apps often need to fetch dynamic data from servers or third-party services. From weather widgets to live feeds, this requires understanding how to request, receive, and manipulate JSON data through APIs. In this lesson, we’ll cover the full process of working with JSON and APIs in JavaScript, including advanced error handling and data manipulation techniques.

What Is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based format for exchanging data. It closely resembles JavaScript objects, but requires double quotes around keys and string values. JSON is the standard format for most APIs.

json
{
  "name": "Ada",
  "age": 25,
  "skills": ["JavaScript", "Python", "React"]
}

JavaScript provides two main methods for working with JSON:

  • `JSON.stringify()` — Converts a JavaScript object into a JSON string.
  • `JSON.parse()` — Converts a JSON string into a JavaScript object.
javascript
const user = { name: 'Nia', age: 22 };
const jsonData = JSON.stringify(user);
console.log(jsonData);

const parsedUser = JSON.parse(jsonData);
console.log(parsedUser.name);

What Is an API?

An API (Application Programming Interface) allows one program to communicate with another. Web APIs provide endpoints that return JSON data. Your JavaScript code can fetch this data and update the web page dynamically.

Fetching Data Using fetch()

The `fetch()` function initiates network requests and returns a Promise. You can chain `.then()` to process the response or `.catch()` to handle errors.

javascript
fetch('https://api.example.com/users')
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

Always check `response.ok` to ensure the HTTP request succeeded before parsing JSON. If there’s a network issue, `.catch()` will handle it.

Async/Await Syntax

Async functions make asynchronous code easier to read and debug by using `await` to pause execution until a Promise resolves.

javascript
async function getUsers() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching users:', error);
  }
}

getUsers();

Manipulating Fetched Data

After fetching JSON, you can manipulate it like any JavaScript object or array. Use `.map()`, `.filter()`, and `.reduce()` to transform data before displaying it.

javascript
async function showUserNames() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const users = await response.json();

  const names = users.map(user => user.name);
  console.log('User names:', names);

  const userList = document.getElementById('userList');
  names.forEach(name => {
    const li = document.createElement('li');
    li.textContent = name;
    userList.appendChild(li);
  });
}

showUserNames();

Error Handling in Depth

Network requests can fail for various reasons: server downtime, incorrect URLs, or connectivity issues. Always wrap fetch calls in `try...catch` and consider fallback strategies like retrying or showing a default message to the user.

Mini Challenge

Fetch 5 random users using the Random User API and display their names and countries on your web page. Ensure you handle errors and use async/await syntax for clean, readable code.

Random User API

MDN Docs: Fetch API