JavaScript Fetch API & HTTP Requests (Advanced)

(Mastering GET, POST, PUT, DELETE requests and advanced fetch handling)


What is the Fetch API?

The Fetch API is a modern interface for making HTTP requests in JavaScript. It returns a Promise and is more powerful and flexible than older methods like XMLHttpRequest.

Basic Structure of Fetch

fetch(url, {
 method: 'GET' | 'POST' | 'PUT' | 'DELETE',
 headers: {},
 body: JSON.stringify(data) // for POST/PUT
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error));

Common HTTP Methods

Method Use Case
GET Retrieve data
POST Send new data
PUT Update existing data
DELETE Remove data

GET Request Example

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(res => res.json())
  .then(data => console.log(data));

POST Request Example

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

PUT Request Example

fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT",headers: { "Content-Type": "application/json" },
ody: JSON.stringify({
 id: 1,
 title: "Updated Title",
 body: "Updated Body",
userId: 1}) })
.then(res => res.json()
).then(data => console.log(data));

DELETE Request Example

fetch("https://jsonplaceholder.typicode.com/posts/1", { method: "PUT",headers: { "Content-Type": "application/json" },
ody: JSON.stringify({
 id: 1,
 title: "Updated Title",
 body: "Updated Body",
userId: 1}) })
.then(res => res.json()
).then(data => console.log(data));

Sending Authorization Headers

fetch("https://api.example.com/data", {
  headers: {
    "Authorization": "Bearer your_token_here"
  }
});

Handling Non-JSON Responses

fetch("/page.html")
.then(response => response.text())
.then(html => document.body.innerHTML =  html);                            

⚠️ Handling HTTP Errors Manually

Fetch does not throw errors for HTTP status codes like 404 or 500. You must handle them:

fetch("/notfound")
.then(response => {
    if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
})
.then(data => console.log(data))
.catch(err => console.error("Fetch error:", err));

Using async/await with Fetch

async function getData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts");
    if (!response.ok) throw new Error("Request failed");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error:", error);
  }
}

Summary

  • The fetch() function is used to perform all kinds of HTTP requests.
  • Always handle .ok to catch non-200 status errors.
  • Use headers and body for POST/PUT requests.
  • Combine fetch with async/await for cleaner syntax.
  • Avoid sending sensitive tokens in the front end without proper security.

🧪 Practice Exercise:

Task:

  1. Create a function that performs a GET request and displays a list of users.
  2. Add a form that submits data to an API using a POST request.
  3. Make a button that deletes a post via a DELETE request.
  4. Add error handling to display a message when fetch fails.
  5. Use async/await to fetch and display data on page load.