Explain it simply
Explain it simply
An endpoint address works like a postal address plus instructions. The URL says which building and which room (the host and the path). The query string is a sticky note with details such as "page 2, twenty items". The headers are the writing on the envelope: who is sending it, which languages you can read, how you prove who you are. The body is the letter inside. If any of those four is wrong or missing, the post office either sends it back or delivers it to the wrong room.
Problem → Why → Solution
The problem: URLs built by joining strings break silently
Your search box works until a user types fish & chips. The code builds the URL by joining strings: base + "/search?q=" + term. The & ends the q parameter after "fish " and starts a new, empty parameter called chips. The server searches for "fish ", so the user gets the wrong results and no error at all. The same family of bug shows up with spaces, #, + and non-ASCII letters.
A second classic: you send JSON with fetch but forget the Content-Type header. fetch labels a string body text/plain, a JSON API refuses or ignores it, and the response says 415 or 400 even though your body looks perfectly fine.
const term = "fish & chips";
const url = "https://api.example.com/v1/search?q=" + term + "&page=2";
console.log(url);
// https://api.example.com/v1/search?q=fish & chips&page=2
// The server reads q = "fish " plus an extra parameter named " chips".Why does this break?
A URL is a string with reserved characters: ? starts the query, & separates parameters, = splits a name from its value, # starts the fragment, and / separates path segments. When your data contains one of them, it must be percent-encoded so the server can tell data from structure. Headers and bodies have their own rules: a body is just bytes, and the Content-Type header is the only thing telling the server how to read them.
Core concept: the jobs of URL, headers and body
A URL has up to six parts. In https://api.example.com:8443/v1/users/42?include=posts&page=2#profile, https is the scheme (the protocol), api.example.com is the host, 8443 is the port (omitted when it is the default for the scheme: 443 for https, 80 for http), /v1/users/42 is the path that identifies the resource, include=posts&page=2 is the query string, and profile is the fragment. The fragment is special: browsers keep it to themselves and never send it to the server, so an API can never read it.
Put identity in the path and options in the query. /users/42 says which user. ?include=posts&page=2 tunes how the answer is shaped: filtering, sorting, paging, choosing fields. A query string is a list of name=value pairs joined by &, and a name may repeat (?tag=a&tag=b). Path parameters are needed to identify the resource, while query parameters are usually optional and come with defaults.
Characters that have a structural meaning in a URL must be percent-encoded when they appear inside data: a space becomes %20 (or + in form-style query strings), & becomes %26, and a non-ASCII letter becomes its UTF-8 bytes written as %XX sequences. In JavaScript use encodeURIComponent(value) for a single value or, better, let URLSearchParams build the whole query string so you cannot forget. Never run encodeURIComponent over a whole URL (it would encode the slashes and colons), and never encode a value twice, or % turns into %25 and the server sees garbage.
Headers carry metadata about the request as name: value lines. Three matter in almost every API call. Accept says which formats you are willing to receive, for example application/json. Content-Type says the format of the body you are sending. Authorization carries your credentials, for example Bearer followed by a token. Header names are case-insensitive, while values such as tokens are not. Do not put secrets in the URL: URLs are routinely recorded in browser history, server logs and referrer headers, while an Authorization header normally is not.
The body is the payload for methods that send data, mostly POST, PUT and PATCH. A GET request has no meaningful body. For JSON APIs the body is JSON text and Content-Type must say application/json; otherwise the server may refuse it with 415 Unsupported Media Type or silently ignore it. In fetch, a string body is labelled text/plain;charset=UTF-8 unless you set the header yourself, which is why this header is the number one cause of "my body arrives empty" bugs.
- URL: where the parcel goes
- Query: handling instructions
- Headers: label on the outside
- Body: what is inside the box
The URL, query and headers tell the server how to treat the request; Content-Type tells it how to read the body.
General pattern: the shape of a URL and a request
scheme://host[:port]/path/to/resource?name=value&name2=value2#fragment
Request line: METHOD /path?query HTTP/1.1
Headers: Name: value (one per line)
(a blank line ends the headers)
Body: optional payload
The fragment (#...) stays in the client and is never sent.What reaches the server is the request line (method, path, query), the headers and the body. The host arrives as a header, and the fragment is not even in the first line. One blank line separates the headers from the body.
Example: take a URL apart and see what the server gets
This script has three parts. First, a URL object takes one URL apart (api.example.com is a placeholder host). Second, a mock server starts and reports what actually reached it. Third, the request is built safely with URL and URLSearchParams: the query contains fish & chips and a fragment is attached. Notice that the "raw URL" line in the output has no fragment.
import http from "node:http";
// 1. Take a URL apart (api.example.com is a placeholder host).
const u = new URL(
"https://api.example.com:8443/v1/users/42?include=posts&page=2#profile"
);
console.log("scheme :", u.protocol);
console.log("host :", u.hostname);
console.log("port :", u.port);
console.log("path :", u.pathname);
console.log("query :", u.search);
console.log("fragment:", u.hash);
// 2. A mock server that reports which parts of the request actually reached it.
const server = http.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
let raw = "";
req.on("data", (chunk) => (raw += chunk));
req.on("end", () => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
rawUrl: req.url,
q: url.searchParams.get("q"),
page: url.searchParams.get("page"),
accept: req.headers.accept,
contentType: req.headers["content-type"],
body: raw,
})
);
});
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;
// 3. Build the request safely: URL for the address, URLSearchParams for the query.
const target = new URL("/v1/search", base);
target.searchParams.set("q", "fish & chips");
target.searchParams.set("page", "2");
target.hash = "results"; // the fragment stays on the client
const res = await fetch(target, {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ sort: "price" }),
});
const seen = await res.json();
console.log("raw URL :", seen.rawUrl);
console.log("q decoded:", seen.q);
console.log("page :", seen.page);
console.log("accept :", seen.accept);
console.log("type :", seen.contentType);
console.log("body :", seen.body);
server.close();Code breakdown
- Parsing a URL
"https://api.example.com:8443/v1/users/42?include=posts&page=2#profile"The URL class splits the string for you, so you never need a hand-written regular expression. Note that protocol keeps its colon (https:), search keeps its ?, and hash keeps its #.
- Server-side parsing
const url = new URL(req.url, "http://localhost");On the server, req.url holds only the path and query (no host), so the URL class needs a base to work with. "http://localhost" exists only for that and does not affect the result.
- Decoded value
q: url.searchParams.get("q"),searchParams.get decodes what was encoded, so fish+%26+chips comes back as fish & chips. Reading + as a space is standard behaviour for URLSearchParams.
- Safe query building
target.searchParams.set("q", "fish & chips");You never encode the value by hand: searchParams turns & into %26 and the space into +. Compare this line with the string-joining approach from the problem section.
- Fragment stays home
target.hash = "results"; // the fragment stays on the clientYou can set a fragment on the URL object, but fetch leaves it out when it sends the request. That is why #results is missing from the raw URL in the output.
- Headers
headers: { Accept: "application/json", "Content-Type": "application/json" },Accept says you can receive JSON, and Content-Type says the body is JSON. The server reads both back and reports them.
- The body
body: JSON.stringify({ sort: "price" }),The body is JSON text, so the server reports body: {"sort":"price"}. Do not mix up page in the query with sort in the body: each place has its own job.
scheme : https:
host : api.example.com
port : 8443
path : /v1/users/42
query : ?include=posts&page=2
fragment: #profile
raw URL : /v1/search?q=fish+%26+chips&page=2
q decoded: fish & chips
page : 2
accept : application/json
type : application/json
body : {"sort":"price"}encodeURIComponent versus URLSearchParams
Each tool produces a slightly different result. Run this script and compare them one by one. In the output encodeURIComponent turns a space into %20 while URLSearchParams turns it into +. Both decode correctly on the server.
const term = "fish & chips/é";
console.log(encodeURIComponent(term));
console.log(new URLSearchParams({ q: term }).toString());
console.log(encodeURI("https://api.example.com/a b?x=1&y=é"));
console.log(decodeURIComponent("fish%20%26%20chips"));
console.log(encodeURIComponent(encodeURIComponent("a b")));| Tool | Use it for | A space becomes |
|---|---|---|
| encodeURIComponent | A single value or one path segment | %20 |
| URLSearchParams | A whole query string | + |
| encodeURI | A complete URL (leaves ? and & alone) | %20 |
The last line shows a mistake: encoding a b twice gives a%2520b, because the second pass turned the % from the first pass into %25. The server decodes only once, so it sees something like a%20b instead of a b.
What happens without a Content-Type
The mock server below behaves like a JSON-only API: it answers 415 unless Content-Type is application/json. The client sends the same body twice, once without the header and once with it. Look at the type the server reports in the error message of the first request.
import http from "node:http";
const server = http.createServer((req, res) => {
let raw = "";
req.on("data", (chunk) => (raw += chunk));
req.on("end", () => {
const type = req.headers["content-type"] ?? "";
if (!type.startsWith("application/json")) {
res.writeHead(415, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "expected application/json, got " + type }));
return;
}
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify({ created: JSON.parse(raw) }));
});
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const url = `http://127.0.0.1:${server.address().port}/users`;
const payload = JSON.stringify({ name: "Alice" });
const bad = await fetch(url, { method: "POST", body: payload });
console.log(bad.status, await bad.text());
const good = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: payload,
});
console.log(good.status, await good.text());
server.close();The first line of the output is 415 with "expected application/json, got text/plain;charset=UTF-8", and the second is 201 with {"created":{"name":"Alice"}}. Other servers do not refuse but silently ignore the body and answer 400 or hand your code an empty object. Either way, always send the header.
Headers you will meet often
| Header | Direction | Purpose |
|---|---|---|
| Accept | Request | The formats you can read, such as application/json |
| Content-Type | Both | The format of the body that comes with the message |
| Authorization | Request | Credentials, for example Bearer <token> |
| Location | Response | The URL of a new resource, usually after a 201 |
| Retry-After | Response | How long to wait before trying again |
In real projects
Endpoint parts in real projects
Every API reference describes an endpoint with these same parts: a method and a URL template, a table of query parameters, the required headers, the schema of the body and an example response. Reading docs is mapping the request you want to write onto those parts. Keeping the version and the resource in the path (/v1/users) and filtering, sorting and paging in the query is a very common layout.
In production a URL is recorded in far more places than one: load balancer logs, CDN logs, browser history, monitoring tools. That is why tokens and personal data such as emails and phone numbers go into a header or the body, never into the URL. API gateways route requests to different services by host and path. And in the browser DevTools Network tab, clicking a request shows these parts separately, which makes debugging easy.
Common mistakes
Common mistakes
1. Building URLs by joining strings
In "?note=" + text, a # inside text cuts the URL short: for item #3 the #3 becomes a fragment and never reaches the server. A & starts a new parameter, and spaces and non-ASCII letters cause trouble too. Always use URL and URLSearchParams.
2. Forgetting Content-Type
Sending JSON.stringify(...) through fetch without a header makes the server see text/plain. The result is a 415, a 400, or, in a framework such as Express, an empty body (req.body is {}). Add Content-Type: application/json whenever you send JSON.
3. Putting a secret in the query string
With ?api_key=abc123 the key lands in logs, browser history and referrers. Some providers accept a key in the query, but when a header (Authorization or the one the provider specifies) is available, use the header instead.
Best practices
Best practices
- Build the URL with new URL(path, base) and the query with searchParams; there is no need to encode by hand.
- Keep the base URL in one configuration place instead of hard-coding it throughout the code.
- Send Accept explicitly, so that when a server can choose between formats you ask for exactly one.
- When you log a URL, mask secrets in the query, and never write the value of an Authorization header.
Mini challenge
Mini challenge: a buildUrl helper
Write buildUrl(), which takes a base URL, a path and a params object and returns the complete URL as a string. Let URLSearchParams do all the encoding.
- Exactly one slash between base and path, whether or not base ends with / or path starts with /
- Skip params whose value is undefined or null
- Repeat the name for array values (tag=a&tag=b)
- Convert every value (numbers included) to a string, then print the three given examples
function buildUrl(base, path, params = {}) {
// TODO: join base and path with exactly one slash between them
// TODO: skip params whose value is undefined or null
// TODO: repeat the name for array values (tag=a&tag=b)
// TODO: let URLSearchParams do all the encoding
// TODO: return the final URL as a string
}
// TODO: print three URLs: a search with q, page and tags, a plain path,
// and a note whose text contains "#"Expected: The output should be: https://api.example.com/v1/search?q=fish+%26+chips&page=2&tag=a&tag=b https://api.example.com/v1/users/42 https://api.example.com/v1/notes?note=item+%233
Show hint
Start with new URL(path.replace(/^\/+/, ""), base.endsWith("/") ? base : base + "/"). Then loop over Object.entries(params), check whether the value is an array, and call url.searchParams.append(name, String(item)). Finally return url.toString().
Show solution
function buildUrl(base, path, params = {}) {
const root = base.endsWith("/") ? base : base + "/";
const url = new URL(path.replace(/^\/+/, ""), root);
for (const [name, value] of Object.entries(params)) {
if (value === undefined || value === null) continue;
for (const item of Array.isArray(value) ? value : [value]) {
url.searchParams.append(name, String(item));
}
}
return url.toString();
}
const host = "https://api.example.com";
const search = { q: "fish & chips", page: 2, tag: ["a", "b"], skip: undefined };
console.log(buildUrl(host, "/v1/search", search));
console.log(buildUrl(host + "/", "v1/users/42"));
console.log(buildUrl(host, "/v1/notes", { note: "item #3" }));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A URL has a scheme, host, port, path, query and fragment, and the fragment is never sent to the server; keep identity in the path and options in the query.
- Build queries with URLSearchParams and encode a single value with encodeURIComponent, never twice.
- Accept names the format you can receive, Content-Type the format of the body you send, Authorization your credentials.
- Always send Content-Type: application/json with JSON, because fetch defaults to text/plain, and keep secrets out of URLs.
RFC 9110 — HTTP Semantics — IETF