The Fetch API

The Fetch API provides a modern, promise-based way to make asynchronous HTTP requests in JavaScript. It replaces older methods like XMLHttpRequest with a cleaner and more powerful syntax.

Illustration of The Fetch API
Illustration of The Fetch API

Basic Usage

Use fetch() to request a resource. It returns a Promise that resolves to a Response object.

📌 Deep Dive: Simple Fetch Request

JAVASCRIPT
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Output
Logs the parsed JSON data or error.

Key Concepts

  • fetch(url, options): Sends a request to the specified URL with optional settings.
  • Response object: Represents the response to the request.
  • Response methods: json(), text(), blob(), etc., to parse response body.
  • Promises: Fetch returns a promise that resolves once headers are received.

Common Response Parsing Methods

Response Body Parsing Methods
MethodDescription
json()Parse the response as JSON.
text()Parse the response as plain text.
blob()Parse the response as a binary large object.
arrayBuffer()Parse the response as an ArrayBuffer for binary data.

Handling HTTP Errors

The Fetch API only rejects a promise on network errors. To handle HTTP errors (like 404 or 500), check the response.ok property.

📌 Deep Dive: Handling HTTP Errors

JAVASCRIPT
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('HTTP error ' + response.status);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Fetch error:', error));
Output
Logs data or an HTTP error message.

Sending Data with Fetch

You can send data along with the request by passing an options object as the second argument to fetch(). Commonly used methods include POST, PUT, PATCH.

📌 Deep Dive: POST Request with JSON Body

JAVASCRIPT
fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ name: 'Alice', age: 30 })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Output
Logs server response to POST.

💡 Important

Always set the appropriate Content-Type header when sending data to ensure the server interprets it correctly.

Summary

  • Fetch is promise-based, allowing clean asynchronous code.
  • Use response.ok to detect HTTP errors.
  • Parse responses using methods like json() or text().
  • Send data by configuring method, headers, and body in the options object.

⚠️ Cross-Origin Requests

Fetch respects CORS. Requests to other origins require the server to allow them via proper headers, or the request will fail.