JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Web Fetch API


Fetching data from a server is a core part of modern web development. The Fetch API is a built-in JavaScript API that allows you to make network requests to get or send data without reloading the page.

It is modern, easy to use, and replaces the older XMLHttpRequest method.

What Is the Fetch API?

The Fetch API provides an interface for making HTTP requests from the browser. You can:

  • Fetch data from an API or server

  • Send data to a server using POST or PUT

  • Work with JSON, text, or binary data

  • Handle responses asynchronously using promises

Key Points:

  • Fetch returns a promise.

  • Promises make it easier to handle asynchronous operations.

  • It supports GET, POST, PUT, DELETE, and other HTTP methods.

Basic Syntax

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

Explanation:

  • url – the address of the server or API.

  • options – an optional object to define HTTP method, headers, body, etc.

  • .then() – handles the response.

  • .catch() – handles any errors.

Fetching Data with GET

The simplest use of Fetch is retrieving data.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json()) // Convert response to JSON
  .then(data => console.log(data))    // Log data
  .catch(error => console.error("Error:", error));

Explanation:

  • The URL returns a post in JSON format.

  • response.json() parses the response body as JSON.

  • Fetch is asynchronous, so it does not block the page.

Example: Displaying Data on the Page

<div id="post"></div>

<script>
fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(res => res.json())
  .then(data => {
    document.getElementById("post").textContent = data.title;
  })
  .catch(err => console.error("Fetch error:", err));
</script>

Explanation:

  • Fetch gets the data.

  • DOM API updates the page dynamically.

  • User sees content without a page reload.

Fetching Multiple Items

You can fetch arrays of data and display them.

fetch("https://jsonplaceholder.typicode.com/posts")
  .then(res => res.json())
  .then(posts => {
    const list = document.createElement("ul");
    posts.slice(0, 5).forEach(post => {
      const item = document.createElement("li");
      item.textContent = post.title;
      list.appendChild(item);
    });
    document.body.appendChild(list);
  })
  .catch(err => console.error(err));

Explanation:

  • Fetch returns all posts.

  • .slice(0,5) takes the first 5 posts.

  • DOM elements are dynamically created to show the data.

Sending Data with POST

Fetch can also send data to a server using POST.

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",           // HTTP method
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({    // Send data as JSON
    title: "My Post",
    body: "This is a test",
    userId: 1
  })
})
.then(res => res.json())
.then(data => console.log("Created:", data))
.catch(err => console.error("Error:", err));

Explanation:

  • method defines the HTTP method.

  • headers tell the server what kind of data is being sent.

  • body contains the data converted to a JSON string.

Using Async/Await with Fetch

async and await make Fetch easier to read.

async function getPost() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}

getPost();

Explanation:

  • async function allows use of await.

  • await fetch() waits for the response.

  • Makes asynchronous code easier to read than multiple .then() calls.

Handling Errors

Fetch only rejects the promise for network errors, not HTTP errors like 404 or 500.

fetch("https://jsonplaceholder.typicode.com/unknown")
  .then(res => {
    if(!res.ok) {
      throw new Error("HTTP error! Status: " + res.status);
    }
    return res.json();
  })
  .then(data => console.log(data))
  .catch(err => console.error("Error:", err));

Explanation:

  • Check res.ok to handle HTTP errors.

  • Throw an error if the response is not successful.

Customizing Headers

You can add authentication tokens, content type, or custom headers.

fetch("https://api.example.com/data", {
  headers: {
    "Authorization": "Bearer YOUR_TOKEN_HERE",
    "Accept": "application/json"
  }
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));

Explanation:

  • Authorization is commonly used for APIs requiring tokens.

  • Headers help control the request and response.

Real-World Example: Fetching and Displaying Users

<ul id="users"></ul>

<script>
async function loadUsers() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const users = await response.json();

    const ul = document.getElementById("users");
    users.forEach(user => {
      const li = document.createElement("li");
      li.textContent = `${user.name} - ${user.email}`;
      ul.appendChild(li);
    });
  } catch (err) {
    console.error("Error fetching users:", err);
  }
}

loadUsers();
</script>

Explanation:

  • Fetches a list of users from an API.

  • Creates a list dynamically using DOM API.

  • Page remains responsive while data is loaded.

Summary of the Tutorial

The Fetch API is a modern, promise-based approach to making HTTP requests in JavaScript. Key points:

  • Fetch is asynchronous and does not block the page.

  • Works for GET, POST, PUT, DELETE, and more.

  • Returns a promise, which can be handled with .then() or async/await.

  • Allows custom headers, JSON handling, and error management.

  • Ideal for loading data from APIs and building dynamic web applications.

With Fetch API, you can create modern, interactive websites that load and send data without full page reloads.


Practice Questions

  1. Write JavaScript code to fetch a single post from https://jsonplaceholder.typicode.com/posts/1 and display the title in a <p> element.

  2. Fetch a list of users from https://jsonplaceholder.typicode.com/users and display their names in an unordered list on the page.

  3. Use the Fetch API to send a POST request with {title, body, userId} to https://jsonplaceholder.typicode.com/posts and log the response.

  4. Write a script that fetches data from an API and handles HTTP errors like 404 or 500 by displaying a custom message.

  5. Create a function using async/await to fetch a post and log the content to the console.

  6. Fetch data from an API and filter the results to display only items with a specific condition (e.g., userId = 1).

  7. Use the Fetch API to send custom headers (like Authorization or Content-Type) in a request and log the JSON response.

  8. Build a mini search function that fetches posts based on a keyword and displays matching results dynamically.

  9. Write code to fetch JSON data from an API and handle network errors using .catch().

  10. Fetch a list of todos from https://jsonplaceholder.typicode.com/todos and display the title with a checkbox indicating the completed status.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top