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. This is 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, and your progress syncs across the web and the CoddyKit app. The Frontend Academy course includes 4 lessons in total.
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=20Why 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-dataQuick 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).
Learn HTML with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 41
- Lessons
- 163
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. 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. The Frontend Academy course includes 4 lessons in total.
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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.
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
- Fetch API: GET POST PUT DELETE
- Axios: Interceptors and Base URL
- Error Handling: HTTP Status Codes
- SWR and React Query for Data Caching