0Pricing
Frontend Academy · Lesson

Fetch API: GET POST PUT DELETE

Make GET requests with fetch, send JSON bodies in POST and PUT requests, and call DELETE endpoints to remove resources.

Fetch API: GET POST PUT DELETE is a free Frontend Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Fetch API

fetch() is the modern browser API for HTTP requests. It returns a Promise that resolves to a Response object. Standard in all modern browsers and Node.js 18+.

Basic GET Request

The simplest fetch — pass a URL, await the response, parse JSON.

async function fetchUsers() {
  const res = await fetch('https://api.example.com/users');
  if (!res.ok) throw new Error('HTTP ' + res.status);
  const users = await res.json();
  return users;
}

POST with JSON Body

Use method, headers, and body. Body must be a string — call JSON.stringify() on the object.

async function createUser(user) {
  const res = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(user)
  });
  if (!res.ok) throw new Error('Failed: ' + res.status);
  return res.json();
}

createUser({ name: 'Alice', email: 'alice@example.com' });

PUT for Full Update

PUT replaces the resource. Send the entire object — fields you omit are usually cleared on the server.

await fetch(`/api/users/${id}`, {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    id, name: 'Alice', email: 'alice@example.com', role: 'admin'
  })
});

PATCH for Partial Update

PATCH updates only the fields you send. Use for partial updates rather than PUT.

await fetch(`/api/users/${id}`, {
  method: 'PATCH',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email: 'new@example.com' })
});

DELETE Request

DELETE typically has no body. The response often returns 204 No Content with no body.

async function deleteUser(id) {
  const res = await fetch(`/api/users/${id}`, { method: 'DELETE' });
  if (!res.ok) throw new Error('Delete failed');
  // 204 No Content — no JSON to parse
}

Authentication Headers

Attach an Authorization header for protected endpoints.

const res = await fetch('/api/me', {
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});

URL Query Parameters

Build query strings with URLSearchParams for safe encoding.

const params = new URLSearchParams({
  q: 'react hooks',
  page: '2',
  pageSize: '20'
});

const res = await fetch(`/api/search?${params}`);
// /api/search?q=react+hooks&page=2&pageSize=20

Why fetch Doesn't Throw on HTTP Errors

fetch only rejects on network failure — a 404 or 500 response still resolves successfully. Always check res.ok (true for 2xx) or res.status and throw manually.

const res = await fetch('/api/users/999');
if (!res.ok) {
  // res.ok is false for 4xx and 5xx
  throw new Error(`Server error ${res.status}: ${await res.text()}`);
}

AbortController for Cancellation

Cancel an in-flight request to prevent stale results — essential for typeahead search and React effect cleanup.

const controller = new AbortController();

fetch('/api/search?q=hooks', { signal: controller.signal })
  .then(res => res.json())
  .catch(err => {
    if (err.name !== 'AbortError') throw err;
  });

// Cancel:
controller.abort();

Sending FormData

For file uploads or multipart forms, pass a FormData object as the body. Don't set Content-Type — the browser adds it with the correct boundary.

const form = new FormData();
form.append('avatar', fileInput.files[0]);
form.append('name', 'Alice');

await fetch('/api/upload', { method: 'POST', body: form });
// no Content-Type header — browser sets multipart/form-data

Quick Check

Why doesn't fetch() throw an error when the server returns a 404 or 500?

Recap: Fetch API

fetch() returns a Promise of Response. Methods: GET (default), POST, PUT, PATCH, DELETE. JSON bodies need JSON.stringify() and Content-Type header. fetch only rejects on network failure — check res.ok manually. URLSearchParams for query strings. AbortController for cancellation. FormData for file uploads (no Content-Type — browser handles it).

Frequently asked questions

Is the “Fetch API: GET POST PUT DELETE” lesson free?

Yes — the full text of “Fetch API: GET POST PUT DELETE” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “Fetch API: GET POST PUT DELETE”?

Make GET requests with fetch, send JSON bodies in POST and PUT requests, and call DELETE endpoints to remove resources. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Frontend Academy?

No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Fetch API: GET POST PUT DELETE” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Frontend Academy lesson?

Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Fetch API: GET POST PUT DELETE
  2. Axios: Interceptors and Base URL
  3. Error Handling: HTTP Status Codes
  4. SWR and React Query for Data Caching
← Back to Frontend Academy