Explain it simply
Request examples in plain language
An API request is like a letter you post. The envelope carries the address (the URL) and what you want done (the method), labels on the envelope (headers) say what language the letter inside is written in, and then comes the letter itself (the body). The server reads the labels first and only then decides how to read the letter.
curl and fetch are two ways of writing that letter. curl is best for quick experiments in a terminal and for copying examples from documentation. fetch is for calling from JavaScript code. Both produce the same HTTP request, so understanding one means you can read the other.
Problem → Why → Solution
The problem: it looks right but the server cannot read it
You write a fetch call to create a user and put the object straight into the body. Nothing throws, yet the server answers 415 or 400, and its log shows the body as the text [object Object]. Then res.json() gives data.id as undefined, or throws a SyntaxError if the server replied with an HTML error page.
// BROKEN: three small mistakes that each look reasonable
const res = await fetch("https://api.example.com/v1/users", {
method: "POST",
body: { name: "Alice", email: "alice@example.com" },
});
const data = await res.json();
console.log(data.id); // undefined, or a SyntaxError if the server answered with HTMLThe client must make headers and body complete
fetch can send a body only as text or bytes. Given an object it converts it with String(object), which gives [object Object]. Given a string it labels the request text/plain, so you must tell the server 'this is JSON' yourself. And fetch rejects only when the network fails, so 404 and 500 are yours to check.
Core concept: the four parts of a request must agree
A request has a method and URL (with its query string), headers and a body. The server combines them to understand what you asked for, so each part must be right and the parts must agree with each other. To send JSON, the body must be JSON text, Content-Type must be application/json, and the method should be one that carries a body: POST, PUT or PATCH. A mismatch rarely raises an error on the client; it shows up as a 400 or 415 from the server, or as wrong data accepted without complaint.
In JavaScript, turn the object into text with JSON.stringify(object) and add Content-Type: application/json to the headers. The server looks at Content-Type to choose a parser; if you omit it, fetch labels a string body text/plain;charset=UTF-8 and the JSON parser never runs. The Accept header says 'please answer in JSON'. Build the query string with URLSearchParams instead of gluing strings together, because it encodes &, spaces and non-ASCII characters for you.
On the response side, fetch has one big surprise: even with a 404 or 500 the promise succeeds and hands you a Response. It rejects only when the network fails, DNS cannot resolve, or the request is aborted. So you must check res.ok (a status from 200 to 299). fetch also does not give up quickly on its own, so add a timeout yourself with AbortSignal.timeout(ms). That is why wrapping fetch in try/catch alone is not enough.
| Part | fetch | curl |
|---|---|---|
| Method | method: "POST" | -X POST (implied by -d) |
| Header | headers: { Name: value } | -H "Name: value" |
| JSON body | body: JSON.stringify(obj) | -d '{...}' or --json '{...}' |
| Query string | new URLSearchParams({...}) | -G --data-urlencode "q=..." |
| Timeout | signal: AbortSignal.timeout(5000) | --max-time 5 |
- Method + URL (build the query safely)
- Headers: Content-Type, Accept, auth
- Body: JSON.stringify(object)
- Send with fetch or curl
- Check res.ok, then parse the body
Headers say how to read the body, so the server understands only when they match it.
General pattern
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify(data),
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const result = await res.json();Describe the request in one options object and read the body only after res.ok has been checked. A GET needs no body and no Content-Type.
Worked example: see what the server sees, three attempts
The script below starts a strict endpoint that accepts only JSON and sends it the same user data in three ways. The server prints the exact Content-Type and body text it received, so you can see with your own eyes what left the client.
In attempt one the object goes out directly, so the server sees [object Object] as text/plain. In attempt two the body is stringified but Content-Type is missing, so the server does not know it is JSON. Only attempt three has both right, and returns 201.
import http from "node:http";
// A strict JSON endpoint: it only accepts bodies labelled application/json.
const server = http.createServer(async (req, res) => {
let raw = "";
for await (const chunk of req) raw += chunk;
const type = req.headers["content-type"] ?? "(none)";
console.log(` server saw: ${type} | ${raw}`);
const reply = (status, body) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (!type.startsWith("application/json")) {
return reply(415, { error: "unsupported_media_type" });
}
try {
reply(201, { id: 1, ...JSON.parse(raw) });
} catch {
reply(400, { error: "invalid_json" });
}
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${server.address().port}/v1/users`;
const user = { name: "Alice", email: "alice@example.com" };
async function attempt(label, init) {
console.log(label);
const res = await fetch(url, { method: "POST", ...init });
console.log(` -> ${res.status} ${await res.text()}`);
}
await attempt("1. object passed as body", { body: user });
await attempt("2. stringified, no header", { body: JSON.stringify(user) });
await attempt("3. stringified + Content-Type", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});
server.close();Code breakdown
- A strict endpoint
if (!type.startsWith("application/json")) {The server checks Content-Type first. If it is not application/json it does not parse the body and answers 415 Unsupported Media Type, which is how many APIs behave.
- Log what arrived
console.log(` server saw: ${type} | ${raw}`);This line is the heart of the lesson. Printing the header and body from the server side shows what the client really sent, with no guessing.
- Bug 1: no stringify
await attempt("1. object passed as body", { body: user });The user object goes straight into body, so fetch applies String(user) and sends [object Object]. Content-Type also becomes text/plain;charset=UTF-8.
- Bug 2: no Content-Type
await attempt("2. stringified, no header", { body: JSON.stringify(user) });The body is valid JSON text, but without Content-Type fetch supplies text/plain. The server treats it as not-JSON and answers 415.
- Correct request
headers: { "Content-Type": "application/json" },Only when the header and JSON.stringify are both present does the server parse the body as JSON and answer 201 Created with the user and an id.
1. object passed as body
server saw: text/plain;charset=UTF-8 | [object Object]
-> 415 {"error":"unsupported_media_type"}
2. stringified, no header
server saw: text/plain;charset=UTF-8 | {"name":"Alice","email":"alice@example.com"}
-> 415 {"error":"unsupported_media_type"}
3. stringified + Content-Type
server saw: application/json | {"name":"Alice","email":"alice@example.com"}
-> 201 {"id":1,"name":"Alice","email":"alice@example.com"}The same request in curl
In curl, -H adds each header and -d adds the body; -d already makes the method POST, so -X POST is not strictly needed. The hosts in these examples are illustrative: api.example.com is not a real service, so substitute your own API's URL.
# api.example.com is an illustrative host, not a real service
curl -X POST "https://api.example.com/v1/users" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-d '{"name":"Alice","email":"alice@example.com"}'The shorter form is --json (available from curl 7.82); it sets Content-Type and Accept to application/json and selects POST for you. -i prints the status line and response headers before the body, which is handy for debugging.
# --json sets Content-Type and Accept for you and implies POST (curl 7.82+)
curl --json '{"name":"Alice","email":"alice@example.com"}' \
"https://api.example.com/v1/users"
# -i prints the status line and response headers before the body
curl -i "https://api.example.com/v1/users/u_1"Quoting differs between shells
These examples target bash and zsh, where JSON inside single quotes is left alone. Windows cmd.exe does not treat single quotes as quotes, so use double quotes and escape the inner " as \". In PowerShell, curl is an alias for Invoke-WebRequest, so write curl.exe.
Query strings, and quoting & in the shell
When a query value contains & or a space, gluing strings together cuts the URL apart. URLSearchParams encodes each value, so q=tea & cake becomes q=tea+%26+cake. The script below compares the two approaches.
const params = new URLSearchParams({ q: "caf\u00e9 & tea", page: "2" });
console.log(`https://api.example.com/v1/search?${params}`);
// Gluing strings together breaks as soon as a value contains & or a space:
console.log("https://api.example.com/v1/search?q=" + "tea & cake" + "&page=2");
console.log(new URLSearchParams({ q: "tea & cake", page: "2" }).toString());The first line shows the é of café becoming %C3%A9 and the space becoming +. The second line, built by gluing, lets the server mistake the & inside the value for a separator, while the third line is correct. The terminal has the same trap: wrap the URL in double quotes, or the shell cuts the command at & and treats the rest as another command. In the curl example below, -G and --data-urlencode build the query string.
# Quote the URL: an unquoted & ends the command in bash and zsh
# -G + --data-urlencode builds the query string and encodes each value
curl -sS --fail-with-body --max-time 5 \
-H "Authorization: Bearer $TOKEN" \
-G "https://api.example.com/v1/users" \
--data-urlencode "role=admin" \
--data-urlencode "q=tea & cake"TOKEN is an environment variable you set in your shell beforehand. Do not type a token straight into the command, because it would remain in your shell history.
What actually goes over the wire
The request that leaves fetch or curl looks like the one below: a start line, one line per header, an empty line, then the body. Content-Length is the number of bytes in the body, and both fetch and curl compute it for you.
POST /v1/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
Content-Length: 44
{"name":"Alice","email":"alice@example.com"}The server's answer has the same layout: a status line, headers, an empty line and a body. A 201 Created with a Location header names the URL of the user that was just created.
HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/users/u_1
Content-Length: 55
{"id":"u_1","name":"Alice","email":"alice@example.com"}fetch does not throw on 404, and timeouts are yours to add
The script below calls an endpoint that answers 404 and looks at res.ok, then calls an endpoint that takes 500 milliseconds with a 100-millisecond timeout.
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/slow") {
const timer = setTimeout(() => res.end("late"), 500);
res.on("close", () => clearTimeout(timer)); // stop if the client gave up
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end('{"error":"not_found"}');
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
const missing = await fetch(`${base}/v1/users/999`);
console.log(missing.ok, missing.status); // false 404: fetch did not throw
console.log(await missing.json());
try {
await fetch(`${base}/slow`, { signal: AbortSignal.timeout(100) });
} catch (err) {
console.log(err.name, "-", err.message);
}
server.close();The first output is false 404: no exception, just a response. The last line is the TimeoutError raised when AbortSignal.timeout cuts the fetch short. You can catch it and decide whether to retry or tell the user.
In real projects
Writing requests in real projects
Most API documentation starts with a curl example, so reading curl means trying a new API takes minutes. In a browser's DevTools Network tab you can right-click a request and choose 'Copy as cURL', which lets you replay in a terminal exactly what a website is doing. When a backend calls another service, fetch is usually wrapped in one helper that adds timeout, retry and error handling, and the whole codebase uses it.
- Tools such as Postman and Insomnia can import curl commands and save requests, which makes sharing them within a team easy.
- SDKs call fetch like this underneath; writing a small client of your own for an API without an SDK follows the pattern of this lesson.
- In production, add a request ID header and log method, URL (without secrets) and status, so problems can be traced.
- In CI, curl --fail-with-body smoke-tests an API: an HTTP error makes curl exit non-zero and fail the pipeline while still printing the response body.
Common mistakes
Common mistakes when sending requests
Forgetting JSON.stringify
Writing body: { name: 'Alice' } makes fetch send [object Object]. Because nothing throws, it is hard to find; printing the body in the server log is the fastest way to catch it.
Leaving out the Content-Type header
A stringified body without the header goes out as text/plain, and the server answers 415 or treats the body as empty. Whenever you send JSON, write the two together.
Assuming fetch throws on 404 and 500
Wrapping fetch in try/catch without checking res.ok treats a 404 as success, and res.json() hands you the error body as if it were data.
Leaving the URL unquoted in the shell
Writing curl https://api.example.com/v1/users?role=admin&page=2 makes bash send curl to the background at & and treat page=2 as a separate command, so the server sees only role=admin. Always wrap the URL in double quotes.
Having no timeout
When a server hangs, a fetch with no timeout waits a long time and your own service's requests pile up behind it. Always add AbortSignal.timeout, or curl --max-time.
Best practices
Best practices
- Whenever you send JSON, add JSON.stringify and Content-Type: application/json together.
- Build query strings with URLSearchParams, and quote URLs in the shell.
- Check res.ok before reading the body, and always set a timeout.
- Read tokens from environment variables instead of typing them into commands.
Mini challenge
Mini challenge: your own request() helper
Write a request(path, options) function that wraps fetch. Build the query with URLSearchParams, use the JSON header and JSON.stringify only when a body is given, add a timeout with AbortSignal.timeout, and throw an Error carrying the status and the server's error when res.ok is false. Try four situations against a local server.
- Build the query with URLSearchParams so a value containing & still works
- Use Content-Type: application/json and JSON.stringify only when a body is given
- Throw Error("HTTP <status>: <error>") when res.ok is false
- Try a search, a user creation, an unknown path and /slow with a 100 ms timeout, printing one line each
import http from "node:http";
// TODO: a local server on port 0 with four routes:
// GET /search?q=... -> 200 { q }
// POST /users -> 201 { id: 1, ...parsed JSON body }
// GET /slow -> answers after 500 ms (stop the timer if the client leaves)
// anything else -> 404 { error: "not_found" }
// TODO: request(path, { method, query, body, timeoutMs }) that
// - builds the query string with URLSearchParams
// - sends JSON (header + JSON.stringify) only when a body is given
// - gives up after timeoutMs with AbortSignal.timeout
// - throws Error("HTTP <status>: <error>") when res.ok is false
// TODO: print one line for each: search with "tea & cake", create a user,
// an unknown path, and /slow with a 100 ms timeoutExpected: query prints {"q":"tea & cake"}, create user prints {"id":1,"name":"Alice"}, missing prints Error: HTTP 404: not_found, and slow prints a TimeoutError.
Show hint
Build new URL(path, baseUrl) and set url.search from URLSearchParams. Read the response body with res.json() before throwing, so you have the server's error text. For a timeout, err.name is TimeoutError.
Show solution
import http from "node:http";
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, "http://local");
let raw = "";
for await (const chunk of req) raw += chunk;
const reply = (status, body) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (url.pathname === "/search") return reply(200, { q: url.searchParams.get("q") });
if (url.pathname === "/users" && req.method === "POST") {
return reply(201, { id: 1, ...JSON.parse(raw) });
}
if (url.pathname === "/slow") {
const timer = setTimeout(() => reply(200, { late: true }), 500);
res.on("close", () => clearTimeout(timer));
return;
}
reply(404, { error: "not_found" });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const baseUrl = `http://127.0.0.1:${server.address().port}`;
async function request(path, { method = "GET", query, body, timeoutMs = 2000 } = {}) {
const url = new URL(path, baseUrl);
if (query) url.search = new URLSearchParams(query).toString();
const headers = { Accept: "application/json" };
if (body !== undefined) headers["Content-Type"] = "application/json";
const res = await fetch(url, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(timeoutMs),
});
const data = res.status === 204 ? null : await res.json();
if (!res.ok) throw new Error(`HTTP ${res.status}: ${data.error}`);
return data;
}
async function show(label, pending) {
try {
console.log(label.padEnd(12), JSON.stringify(await pending));
} catch (err) {
console.log(label.padEnd(12), `${err.name}: ${err.message}`);
}
}
await show("query", request("/search", { query: { q: "tea & cake" } }));
await show("create user", request("/users", { method: "POST", body: { name: "Alice" } }));
await show("missing", request("/nothing"));
await show("slow", request("/slow", { timeoutMs: 100 }));
server.close();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A server understands a request only when its method, URL, headers and body agree.
- To send JSON, pair JSON.stringify(object) with Content-Type: application/json, or the server sees [object Object] or text/plain.
- fetch does not reject on 404 or 500, so check res.ok and add a timeout with AbortSignal.timeout.
- In curl use -H, -d, --json and -G, quote the URL, and build query strings with URLSearchParams.
RFC 9110 — HTTP Semantics — IETF