← Back to Chapters

JavaScript Fetch API

⚡ JavaScript Fetch API

? Quick Overview

The Fetch API provides a modern, promise-based way to make HTTP requests from JavaScript. It acts as a cleaner, more powerful alternative to XMLHttpRequest and is commonly used to:

  • Retrieve data from REST APIs (GET requests).
  • Send data to servers (POST, PUT, DELETE, etc.).
  • Handle responses asynchronously using Promise or async/await.

Fetch is built into modern browsers and returns a Promise that resolves to a Response object.

? Key Concepts

  • fetch(url, options?) – main function to make a request.
  • Promise-based – operations are asynchronous and use .then() or async/await.
  • Response object – represents the HTTP response; you often call response.json() or response.text().
  • Error handling – use .catch() or try...catch to handle network errors.
  • Does not auto-fail on HTTP errors – Fetch only rejects on network failure, not on HTTP status like 404 or 500.
  • Options object – lets you set method, headers, body, and more.

? Syntax & Theory

Basic syntax of the Fetch API looks like this:

? View Basic Syntax Pattern
fetch(url, [options])
.then(response => {
// inspect or transform response here
})
.catch(error => {
// handle network errors here
});

Where:

  • url is the endpoint you are calling (string).
  • options is an optional object to configure:
    • method – HTTP method (GET, POST, PUT, DELETE, etc.).
    • headers – custom headers like Content-Type.
    • body – data sent with the request (e.g. JSON string).

? Code Examples

? Basic GET Request with Promises

A simple GET request that fetches JSON data and logs it to the console.

? View Code Example
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

⏱️ Using Async/Await with Fetch

async/await makes asynchronous code look more like synchronous code and is easier to read for complex flows.

? View Code Example
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();

? Sending Data with POST

You can send JSON data to a server by using the options object with method, headers, and body.

? View Code Example
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'John', age: 30 })
})
.then(response => {
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
return response.json();
})
.then(data => console.log('Saved:', data))
.catch(error => console.error('Error:', error));

? Live Output & Explanation

Below is a small interactive demo. It uses fetch to load a sample post from a public API and renders the title and body on the page.

? Result

Click the button to fetch and display a sample post using the Fetch API.

? What Happens Internally

  1. fetch() sends a GET request to the API URL.
  2. When the response arrives, the code calls response.json() to parse it.
  3. The parsed data (a JavaScript object) is used to build some HTML.
  4. The HTML is injected into the page so you can see the result.
  5. If there is a network error or HTTP error, an error message is shown instead.

? Tips & Best Practices

  • Prefer async/await for complex flows – it makes the logic easier to follow than chaining many .then() calls.
  • Always check response.ok and handle non-2xx status codes explicitly.
  • Use try...catch or .catch() to handle network errors and avoid silent failures.
  • Always convert the response to the correct format (response.json(), response.text(), response.blob(), etc.).
  • Keep API URLs and keys in configuration (not hard-coded everywhere in your code).

? Try It Yourself

  • Write a script that makes a GET request to a public API (e.g. posts, users, or jokes) and logs the result to the console.
  • Create a small page with a button that triggers a Fetch call and displays the result in the DOM instead of the console.
  • Implement a POST request using Fetch that sends a JSON body (for example, a new todo item) and logs the server response.
  • Modify your Fetch code to:
    • Check response.ok.
    • Throw custom errors for HTTP status codes like 404 or 500.
    • Show user-friendly error messages on the page.
  • Refactor one of your older projects that uses XMLHttpRequest and rewrite the requests using the Fetch API.