← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 3 of 26

JS Fetch API

What Is Fetch?

The Fetch API makes HTTP requests and returns a Promise. That Promise resolves once the response headers arrive, not once the full body has downloaded — reading the body itself requires a separate step like response.json().

Example: What Is Fetch?

javascript
fetch("data.php")
  .then(response => console.log(response)); // Promise resolves once headers arrive

Handling Responses

Check the response before using its data. A fetch() Promise only rejects on network failure; a 404 or 500 response is still a successful fetch, so check response.ok or response.status before trusting the data.

Example: Handling Responses

javascript
fetch("data.php")
  .then(response => {
    if (!response.ok) {
      console.log("Request failed:", response.status);
      return;
    }
    return response.json();
  })
  .then(data => console.log(data));

POST Request

Fetch can send JSON data with a POST request. Send a POST by passing an options object with method: POST, a JSON.stringify()'d body, and a Content-Type header set to application/json.

Example: POST Request

javascript
fetch("save.php", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Sam" }),
}).then(response => console.log(response.status));

Error Handling

Network requests can fail. Use try...catch with async functions. Because fetch() doesn't reject on HTTP error statuses, wrapping the whole call in try/catch alone isn't enough — you also need an explicit check for response.ok inside the try block.

Example: Error Handling

javascript
async function loadData() {
  try {
    const response = await fetch("data.php");
    if (!response.ok) throw new Error("Request failed: " + response.status);
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.log("Error:", error.message);
  }
}
loadData();

Practical API Use

Fetch is useful for loading API data and sending data to a server. A typical pattern combines fetch(), response.json(), and error handling to load data from an API and update the page once it arrives.

Example: Practical API Use

javascript
async function loadUser() {
  const response = await fetch("user.php");
  const data = await response.json();
  document.body.innerHTML = `<p>${data.message}</p>`;
}
loadUser();

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.