POST Requests
Sending data — JSON body, Content-Type, and handling the response
Skills taught: api.post-fetch, api.content-type, api.request-body, api.put-patch-delete
Sending data with fetch()
// ── POST — create a new resource ──
async function createPost(data) {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data), // object → JSON string
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json(); // → { id: 101, ...data }
}
const post = await createPost({
title: 'Hello World',
body: 'My first post',
userId: 1,
});
console.log('Created:', post.id, post.title);
// → Created: 101 Hello World
// ── PATCH — partial update ──
async function updatePost(id, changes) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(changes), // only the changed fields
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
await updatePost(1, { title: 'Updated Title' });
// ── DELETE ── (usually no body)
async function deletePost(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'DELETE',
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
// 204 No Content — no body to parse
}
// ── Helper for any method ──
async function api(method, path, data) {
const opts = { method, headers: {} };
if (data) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(data);
}
const res = await fetch('https://jsonplaceholder.typicode.com' + path, opts);
if (!res.ok) throw new Error(`${method} ${path} → ${res.status}`);
if (res.status === 204) return null;
return res.json();
}
Frequently Asked Questions
Do I always need Content-Type for POST requests?
For JSON bodies, yes — always set Content-Type: 'application/json'. For FormData (file uploads), do NOT set Content-Type manually — the browser sets it automatically with the correct multipart boundary. For URLSearchParams (form encoding), the browser also sets the correct Content-Type automatically. The rule: only set Content-Type manually for JSON (application/json) and raw text bodies.