JavaScript Fetch API

The Fetch API is used to request resources from a server. It's a modern way to perform HTTP requests in JavaScript using Promises.

GET Request


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

Using async/await


async function fetchPost() {
  try {
    let res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    let data = await res.json();
    console.log(data);
  } catch (err) {
    console.error("Failed:", err);
  }
}
fetchPost();
            

POST Request

Send data to the server using POST:


fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    title: "Hello World",
    body: "This is a post",
    userId: 1
  })
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
            

Common Response Handling

Check for success before using res.json():


async function safeFetch() {
  let res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  if (!res.ok) {
    throw new Error("HTTP error " + res.status);
  }
  let data = await res.json();
  console.log(data);
}
            

Practice Task

Fetch a random user from the API and display their name:


async function getUser() {
  let res = await fetch("https://jsonplaceholder.typicode.com/users/1");
  let user = await res.json();
  console.log("User:", user.name);
}
getUser();