Explain it simply
APIs in plain language
An API (Application Programming Interface) is a set of rules in which one program promises another: ask me like this and I will answer like that. Web APIs use HTTP: your JavaScript sends a request to a URL and the server sends back a response, usually in JSON.
Think of a restaurant menu and an order slip. The menu, the API documentation, says what you can order, and the slip, the request, must be filled in the agreed format: which dish, how many. You never need to know what happens inside the kitchen, the server; you only care about the plate that comes back, the response.
Problem → Why → Solution
The problem: a 'secret' key in the frontend
While trying out a payment API, you put the secret key in a .env file and call the API straight from frontend code. It feels safe because the key is not typed into the code. In reality, variables with Vite's VITE_ prefix or Next.js's NEXT_PUBLIC_ prefix are pasted into the JavaScript bundle as plain text at build time. Anyone who visits the site can copy the key from DevTools.
// Runs in the visitor's browser: this value ends up inside the bundle
const key = import.meta.env.VITE_PAYMENTS_SECRET_KEY;
await fetch("https://api.payments.example/v1/charges", {
method: "POST",
headers: { Authorization: `Bearer ${key}` }, // visible in the Network tab
body: JSON.stringify({ amount: 5000, currency: "usd" }),
});A browser cannot keep a secret
Every piece of code, variable and request header that reaches the browser can be seen by the user. Make calls that need a secret key from your own server, a backend or serverless function, and let the browser call only that server. The only keys that belong in frontend code are ones the provider designed to be public, such as a domain-restricted publishable key.
Core concept: request, response and the contract
An HTTP request has four parts. The method (GET, POST, PUT, PATCH, DELETE) says what you want to do. The URL says which resource, and may carry a query string such as ?page=2&limit=10. Headers carry metadata: Accept (the format you want back), Content-Type (the format of the body you send) and Authorization (who you are). The body is the data you send, mostly with POST, PUT and PATCH.
A response has three parts: a status code, headers and a body. The first digit of the status code tells you its group, so you can decide how to handle even a code you have never seen before.
| Group | Meaning | Examples |
|---|---|---|
| 2xx | success | 200 OK, 201 Created, 204 No Content |
| 3xx | look elsewhere | 301, 304 Not Modified |
| 4xx | the client's request is wrong | 400, 401, 403, 404, 429 |
| 5xx | the server failed | 500, 502, 503 |
The API contract, its documentation or an OpenAPI spec, defines for each endpoint the method, the request and response shapes, the possible status codes, how to authenticate, rate limits such as 60 requests per minute, and versioning. GET for reading and POST for creating is the general convention, but each API's own documentation is what counts.
From the client's side, an API call can fail in three distinct ways: a network error (no response at all), an HTTP error (a 4xx or 5xx response) and an invalid payload (a 2xx response whose data has the wrong shape). Each needs different handling, so keep them apart. A 5xx or a network error may succeed on a later retry; a 4xx usually will not until the request itself is fixed.
- Method + URL: what, and where
- Headers: format and identity
- Body: the data you send, if any
- Get back status, headers, body
- Split network/HTTP/payload errors
Everything you put in a request is visible in the browser's Network tab; keep secrets on the server side.
General pattern
METHOD https://host/path?key=value <- request line
Header-Name: value <- headers (Accept, Authorization...)
{ "json": "body" } <- body (POST, PUT, PATCH)
HTTP/1.1 STATUS Reason <- response status line
Content-Type: application/json <- response headers
{ "json": "result" } <- response bodyEvery HTTP message has this shape: a first line, headers, an empty line and an optional body. In JavaScript, request objects, fetch options and Response objects expose these same parts as properties.
Worked example: building requests and reading a response
A buildRequest helper turns a method, path, query, body and token into a complete request, and then a JSON response the server might send is parsed. No network is involved, on purpose: a request is just data until you send it, and printing it lets you see every part.
// An API call is a request (method, URL, headers, body) and a response
// (status, headers, body). Here both are plain objects you can inspect.
const baseUrl = "https://api.example.com";
function buildRequest(method, path, { query = {}, body, token } = {}) {
const url = new URL(path, baseUrl);
for (const [key, value] of Object.entries(query)) {
url.searchParams.set(key, String(value));
}
const headers = { Accept: "application/json" };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (token) headers.Authorization = `Bearer ${token}`;
return { method, url: url.href, headers, body: body && JSON.stringify(body) };
}
const listUsers = buildRequest("GET", "/users", { query: { page: 2, limit: 1 } });
console.log(listUsers.method, listUsers.url);
const createUser = buildRequest("POST", "/users", {
body: { name: "Aung Kyaw", email: "aung@example.com" },
token: "demo-token",
});
console.log(createUser.method, createUser.url);
console.log("Headers:", Object.keys(createUser.headers).join(", "));
console.log("Body:", createUser.body);
// A response the server could send back for the GET request
const response = {
status: 200,
body: '{"page":2,"total":3,"users":[{"id":2,"name":"Su Su"}]}',
};
const data = JSON.parse(response.body);
console.log(`Status: ${response.status}`);
console.log(`Page ${data.page}: ${data.users[0].name} (${data.total} users in total)`);Code breakdown
- Safe URL building
const url = new URL(path, baseUrl);The URL constructor joins the path to the base, and searchParams.set encodes special characters such as spaces and & correctly, which is safer than gluing strings together.
- Headers depend on the request
if (body !== undefined) headers["Content-Type"] = "application/json";Content-Type describes the body you send, so it is added only when there is a body. Accept describes what you want back, so every request carries it.
- Identify the caller
if (token) headers.Authorization = `Bearer ${token}`;A Bearer token means 'whoever holds this token'. A demo-token is used here; send real secrets only from a server.
- Query string in the URL
const listUsers = buildRequest("GET", "/users", { query: { page: 2, limit: 1 } });A GET request has no body, so filters and pagination travel in the query string, which appears in the output as ?page=2&limit=1.
- Response body is text
const data = JSON.parse(response.body);A body arrives over the network as text. Only after JSON.parse can you read properties such as data.users[0].name.
GET https://api.example.com/users?page=2&limit=1
POST https://api.example.com/users
Headers: Accept, Content-Type, Authorization
Body: {"name":"Aung Kyaw","email":"aung@example.com"}
Status: 200
Page 2: Su Su (3 users in total)How an API knows who is calling
Most APIs recognise the caller from a credential sent with every request, because the server does not remember earlier requests. The table compares the three common styles; the authentication section of the API's documentation says which one it accepts.
| Style | How it is sent | Typical use |
|---|---|---|
| API key | X-API-Key header or query | server-to-server calls |
| Bearer token | Authorization: Bearer <token> | logged-in users, OAuth |
| Session cookie | sent automatically by the browser | same-site web apps |
In real projects
APIs in real projects
Almost every frontend app calls more than one API: its own backend plus third-party services for maps, payments or email. Teams usually start from the example requests, responses and status table in the documentation and turn them into client functions.
- Backend-for-frontend: the browser calls your own endpoint such as /api/checkout, and your server calls the payment provider with the secret key, which never reaches the browser.
- On 429 Too Many Requests, the client waits the number of seconds given in the Retry-After header before trying again; hammering the API immediately only makes it worse.
- APIs are versioned with /v1/ in the path or a version header, so when the server changes a response shape, older apps do not break overnight.
Common mistakes
Common mistakes with APIs
Shipping a secret key to the frontend
No VITE_ or NEXT_PUBLIC_ variable, minified bundle or obfuscation hides a key. If one has leaked, rotate it immediately and move the call to the server side.
Building query strings by concatenation
"/search?q=" + term breaks when term contains & or #, and can even inject extra parameters. Use URLSearchParams or encodeURIComponent.
Lumping the three failure kinds together
Showing 'something went wrong' for every error leaves users stuck. Offline means 'check your connection', 401 means 'please log in again', and an invalid payload is a bug to log and report.
Retrying a 4xx in a loop
Sending a request that got 400 or 404 again will not fix it; it only burns through your rate limit faster. Retry only network errors, 5xx responses and a 429 with Retry-After, and cap the number of attempts.
Best practices
Best practices
- Read the documented example request and response before writing code for a new endpoint.
- Keep the base URL, auth header and timeout together in one client function.
- Do not assume every 2xx carries correct data; check the fields you rely on.
Mini challenge
Mini challenge: a getUser that classifies outcomes
Write getUser(id, fetchFn). It must never throw; instead it always returns an object with a kind field: "ok", "invalid-payload", "http-error" or "network-error". The provided fakeApi produces one situation for each user id from 1 to 5.
- Return { kind: "network-error", message } when fetchFn rejects
- Return an http-error with the status when response.ok is false, adding Retry-After as a number if present
- isUser checks for a numeric id and a string name; otherwise return invalid-payload
- Loop over ids 1 to 5 and print each result
// Fake API: each user id triggers a different outcome.
const routes = {
"/users/1": () => Response.json({ id: 1, name: "Aung Kyaw" }),
"/users/2": () => Response.json({ id: 2 }), // the name field is missing
"/users/3": () => Response.json({ error: "User not found" }, { status: 404 }),
"/users/4": () => new Response(null, { status: 429, headers: { "Retry-After": "30" } }),
};
async function fakeApi(url) {
const route = routes[new URL(url).pathname];
if (!route) throw new TypeError("fetch failed"); // like DNS or a dropped connection
return route();
}
function isUser(value) {
// TODO: true only for a numeric id and a string name
}
async function getUser(id, fetchFn = fetch) {
// TODO: 1. call fetchFn; on rejection return a "network-error" result
// TODO: 2. if !response.ok return an "http-error" result (+ retryAfter)
// TODO: 3. parse JSON; return "invalid-payload" or "ok" with the user
}
// TODO: print id and getUser(id, fakeApi) for ids 1 to 5Expected: id 1 → kind 'ok' with Aung Kyaw, 2 → 'invalid-payload', 3 → 'http-error' with status 404, 4 → status 429 with retryAfter: 30, 5 → 'network-error' with message 'fetch failed'.
Show hint
Wrap only the fetchFn call in try/catch, so only network errors land there. Header names are case-insensitive, so response.headers.get("retry-after") works.
Show solution
// Fake API: each user id triggers a different outcome.
const routes = {
"/users/1": () => Response.json({ id: 1, name: "Aung Kyaw" }),
"/users/2": () => Response.json({ id: 2 }), // the name field is missing
"/users/3": () => Response.json({ error: "User not found" }, { status: 404 }),
"/users/4": () => new Response(null, { status: 429, headers: { "Retry-After": "30" } }),
};
async function fakeApi(url) {
const route = routes[new URL(url).pathname];
if (!route) throw new TypeError("fetch failed"); // like DNS or a dropped connection
return route();
}
function isUser(value) {
return typeof value?.id === "number" && typeof value?.name === "string";
}
async function getUser(id, fetchFn = fetch) {
let response;
try {
response = await fetchFn(`https://api.example.com/users/${id}`);
} catch (error) {
return { kind: "network-error", message: error.message };
}
if (!response.ok) {
const retryAfter = response.headers.get("retry-after");
return retryAfter
? { kind: "http-error", status: response.status, retryAfter: Number(retryAfter) }
: { kind: "http-error", status: response.status };
}
const data = await response.json();
if (!isUser(data)) return { kind: "invalid-payload", data };
return { kind: "ok", user: data };
}
async function main() {
for (const id of [1, 2, 3, 4, 5]) {
console.log(id, await getUser(id, fakeApi));
}
}
main();Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A request has a method, URL, headers and body; a response has a status, headers and body.
- The first digit of a status code gives its group: 2xx success, 4xx client error, 5xx server error.
- An API call can fail as a network error, an HTTP error or an invalid payload.
- Any key that reaches the browser is public; make calls that need secrets from a server.
MDN — Fetch API — MDN Web Docs