JavaScript

JSON Fetch Wrapper

by @admin
9h ago
Apr 28, 2026
Public
A thin wrapper around fetch that automatically serialises the request body to JSON, sets the Content-Type header, parses the response as JSON, and throws a descriptive error on non-OK responses. Covers the boilerplate needed for 95% of REST API calls in a single reusable function.
JavaScript
async function apiFetch(url, { method = 'GET', body, headers = {}, ...rest } = {}) {
  const opts = {
    method,
    headers: { 'Content-Type': 'application/json', ...headers },
    ...rest,
  };
  if (body !== undefined) opts.body = JSON.stringify(body);

  const res = await fetch(url, opts);
  const data = await res.json().catch(() => null);

  if (!res.ok) {
    const msg = data?.message ?? data?.error ?? `HTTP ${res.status}`;
    throw Object.assign(new Error(msg), { status: res.status, data });
  }
  return data;
}

// Usage
const user  = await apiFetch('/api/users/1');
const saved = await apiFetch('/api/snippets', { method: 'POST', body: { title: 'Hi', code: '...' } });
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.