JavaScriptJavaScript

Fetch API Example

This Fetch API example shows a clean GET request flow with error handling and JSON parsing. It is a practical baseline for client-side data loading in dashboards, settings pages, and browser-based tools.

Concise explanation

  • Call `fetch()` with the URL and any request options you need, such as headers.
  • Check `response.ok` before parsing the body so non-2xx responses fail clearly.
  • Use `response.json()` when the endpoint returns JSON data.
  • Return the parsed payload so the caller can compose the request with `.then()` or `await`.

Code snippet

JavaScript

async function loadUser(userId) {
  const response = await fetch(`https://api.example.com/users/${userId}`, {
    headers: {
      Accept: "application/json",
    },
  });

  if (!response.ok) {
    throw new Error(`Request failed with ${response.status}`);
  }

  return response.json();
}

loadUser(42).then(console.log).catch(console.error);

Quick result

A successful request resolves to parsed JSON you can render directly in the UI or store in application state.

Console output
{
  "id": 42,
  "name": "Alex",
  "role": "admin"
}

If the response status is not OK, this example throws early so failures are easier to debug.

Related examples

Related Tools

A Good Default Fetch Pattern

A solid Fetch example does more than call the endpoint. It also checks the response status, handles errors in one place, and returns parsed data in a predictable format.

That makes the snippet easier to reuse in React components, plain browser scripts, or utility functions shared across a codebase.

Common Fetch Follow-Ups

After the basic GET pattern is working, developers usually add authentication headers, POST bodies, loading states, and retry logic. Those concerns are easier to introduce when the original request function already separates network errors from successful JSON parsing.

For larger apps, this pattern also maps cleanly into wrappers around `fetch` so repeated request logic stays centralized.