Building Custom APIs
Published by Brayan K
Master the art of designing clean, reusable API layers using fetch, async/await, and production-grade patterns used by professional developers.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give the caller one dependable result
A useful API layer answers a specific question: what does the rest of the application receive when a request succeeds, and what happens when it fails? Start with a catalogue endpoint that supplies one product. The interface should return a product, rather than making each screen repeat URL construction, status checks and field names.
This lesson builds a small, testable boundary. Its examples use an injected request function and real Response objects with fixed bodies. They do not contact a server or require an account. The production transport can be fetch; replacing it with a local fixture lets us check success and failure deliberately. Fetch API owns making HTTP requests, and Async/Await owns waiting for promises.
async function readProduct(request, id) {
const response = await request("/products/" + id);
if (!response.ok) throw new Error("HTTP " + response.status);
const data = await response.json();
return { id: data.id, label: data.display_name };
}
const calls = [];
const request = async path => {
calls.push(path);
return new Response('{"id":7,"display_name":"Desk lamp"}', {
status: 200,
headers: { "Content-Type": "application/json" }
});
};
const product = await readProduct(request, 7);
console.log(calls.join(", "));
console.log(product.id, product.label);
// ✅ Expected output:
// /products/7
// 7 Desk lampThe fixture records the requested path, so the check covers the outgoing request as well as the returned value. Normalising display_name to label gives the caller one vocabulary. This first version still trusts the body shape; we will close that gap before composing the final client.
A fulfilled request can describe an HTTP failure
Receiving a response is different from receiving the data you wanted. Fetch normally fulfils its promise for HTTP error statuses such as 404; the caller must inspect the response. Check ok before treating an error page as a successful product. A network rejection has no HTTP response to inspect.
const response = await Promise.resolve(new Response("Not found", {
status: 404,
headers: { "Content-Type": "text/plain" }
}));
console.log(response.status);
console.log(response.ok);
console.log(await response.text());
// ✅ Expected output:
// 404
// false
// Not foundasync function readJson(response) {
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
}
await readJson(new Response("<h1>Unavailable</h1>", {
status: 503,
headers: { "Content-Type": "text/html" }
}));
// ✅ Expected error:
// Error: HTTP 503The error identifies the failed HTTP request. Parsing this HTML as JSON first would produce a parsing error and obscure that status. A larger application can keep the status on a custom error object; Error Handling Patterns in Large JS Apps owns that error model and the user-facing recovery decision. Do not catch every failure and return an empty product: that turns failure into apparently valid data.
async function loadProduct(request) {
const response = await request("/products/7");
if (!response.ok) throw new Error("HTTP " + response.status);
return response.json();
}
const request = async () => {
throw new TypeError("Transport unavailable");
};
try {
await loadProduct(request);
} catch (error) {
console.log(error.name);
console.log(error.message);
}
// ✅ Expected output:
// TypeError
// Transport unavailableParsing JSON does not validate a product
JSON can hold a string, a number, null, an array or an object with the wrong fields. A successful parse only tells you that the text is JSON. Validate the fields your interface promises before returning a normalised product. Keep that check at the boundary so callers can rely on the result.
function productFrom(data) {
if (data === null || typeof data !== "object" || Array.isArray(data) ||
!Number.isInteger(data.id) || data.id <= 0 ||
typeof data.display_name !== "string" ||
data.display_name.trim() === "") {
throw new TypeError("Invalid product response");
}
return { id: data.id, label: data.display_name.trim() };
}
const response = new Response('{"id":7,"display_name":" Desk lamp "}');
const product = productFrom(await response.json());
console.log(product.id);
console.log(product.label);
// ✅ Expected output:
// 7
// Desk lampfunction productFrom(data) {
if (data === null || typeof data !== "object" || Array.isArray(data) ||
!Number.isInteger(data.id) || data.id <= 0 ||
typeof data.display_name !== "string" ||
data.display_name.trim() === "") {
throw new TypeError("Invalid product response");
}
return { id: data.id, label: data.display_name.trim() };
}
const response = new Response('{"id":"7","display_name":"Desk lamp"}');
productFrom(await response.json());
// ✅ Expected error:
// TypeError: Invalid product responseThe string ID is rejected rather than silently converted. That is a deliberate interface choice: if the server contract permits string IDs, define and test that different contract. The check above validates the fields used here; it is not a universal schema validator and does not make the returned label safe to insert as HTML.
A 204 response is another distinct case: it has no body to parse. A helper used for operations that legitimately return no content can represent that result as null. An endpoint promising a product should instead reject a missing product. Choose that behaviour explicitly.
async function readOptionalJson(response) {
if (!response.ok) throw new Error("HTTP " + response.status);
if (response.status === 204) return null;
const mediaType = (response.headers.get("Content-Type") || "")
.split(";")[0].trim().toLowerCase();
if (mediaType !== "application/json") {
throw new TypeError("Expected application/json");
}
return response.json();
}
console.log(await readOptionalJson(new Response(null, { status: 204 })));
const response = new Response('{"saved":true}', {
headers: { "Content-Type": "application/json; charset=utf-8" }
});
console.log((await readOptionalJson(response)).saved);
// ✅ Expected output:
// null
// trueThis helper accepts one documented media type. Some APIs use a vendor type ending in +json; add that only when the API contract calls for it. A matching header still does not guarantee valid JSON, so a rejected json() promise must remain visible to the caller.
Merge request options without erasing your defaults
Object spread is shallow. If you construct a default headers object and then spread an options object containing its own headers, the later property replaces the whole earlier object. Use Headers to combine header inputs, then place the final merged headers after the other options.
const options = { headers: { "X-Trace": "demo" } };
const broken = {
headers: { Accept: "application/json" },
...options
};
console.log(new Headers(broken.headers).has("Accept"));
console.log(new Headers(broken.headers).get("X-Trace"));
// ✅ Expected output:
// false
// demofunction jsonOptions(options = {}) {
const headers = new Headers({ Accept: "application/json" });
new Headers(options.headers).forEach((value, name) => {
headers.set(name, value);
});
return { ...options, headers };
}
const supplied = new Headers({ "X-Trace": "demo" });
const options = jsonOptions({ method: "GET", headers: supplied });
console.log(options.method);
console.log(options.headers.get("Accept"));
console.log(options.headers.get("X-Trace"));
console.log(supplied.has("Accept"));
// ✅ Expected output:
// GET
// application/json
// demo
// falseThe caller may override a default in this version. Headers that enforce an application policy need a different rule: set them after caller input, or reject attempts to supply them. Also distinguish Accept, which asks for a response format, from Content-Type, which describes a request body. Do not attach a JSON body type to every request regardless of its actual body.
Keep destinations and credentials inside the contract
An authenticated client should not attach a credential to an arbitrary URL supplied by its caller. Restrict the destination before choosing credentials. An origin is the scheme, host and port; a string that merely starts with the expected hostname is not an origin check. The following fixture rejects another origin without calling its transport.
function catalogueUrl(path) {
const base = new URL("https://api.example.test/v1/");
const target = new URL(path, base);
if (target.origin !== base.origin || target.username || target.password ||
!target.pathname.startsWith("/v1/")) {
throw new TypeError("Destination outside the catalogue API");
}
return target;
}
let calls = 0;
const request = async () => { calls += 1; };
try {
await request(catalogueUrl("https://other.example.test/products/7"));
} catch (error) {
console.log(error.message);
}
console.log(calls);
console.log(catalogueUrl("products/7").pathname);
// ✅ Expected output:
// Destination outside the catalogue API
// 0
// /v1/products/7This check limits the initial destination. It is not a complete authentication system or a proof about redirects, server permissions or CORS. A real credential policy must account for those too. For a narrow client, accepting a product ID and constructing the route internally is easier to reason about than accepting any URL.
Authentication tokens are sensitive data. localStorage is readable by scripts in the same origin, so it is not a safe exception for session tokens. OWASP advises against storing session identifiers there. HttpOnly cookies can prevent JavaScript from reading a cookie, but authentication still needs an appropriate server design and CSRF protection. Client-Side Security Essentials (XSS, CSRF, Sanitisation) owns those choices; Web Storage APIs (localStorage, sessionStorage, IndexedDB) owns persistence mechanics.
A wrapper also cannot decide that every failed request is safe to repeat: a write may already have reached the server. Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns bounded retries and cancellation. This client leaves those policies explicit instead of silently retrying writes.
Keep private responses out of a shared URL-only cache: the same URL can represent different users. If adding caching later, define identity, expiry and invalidation first; storing a promise or object in a Map does not settle those rules.
Complete the response boundary
Fill the three blanks to reject unsuccessful statuses, read the response body and return the label. Each hint gives the literal replacement. Run the completed program, then replace the successful fixture with a 404 response and confirm that it rejects before returning a label.
async function labelFrom(response) {
if (___) throw new Error("HTTP " + response.status);
// 👉 replace ___ with !response.ok
const data = await ___;
// 👉 replace ___ with response.json()
if (typeof data.display_name !== "string") {
throw new TypeError("Missing display_name");
}
return ___;
// 👉 replace ___ with data.display_name.trim()
}
const response = new Response('{"display_name":" Shelf "}', {
status: 200,
headers: { "Content-Type": "application/json" }
});
console.log(await labelFrom(response));
// ✅ Expected output:
// ShelfThe exercise deliberately uses a known object fixture. The independent client below must also reject null, arrays and malformed product fields; copying only this smaller exercise would leave that part of the interface unchecked.
Build a catalogue client with a checked failure path
Write createCatalogueClient(request). It returns an object with an async getProduct(id) method. Require a positive integer ID before calling the transport. Construct /products/ID, request JSON, reject an unsuccessful HTTP status, and require a product with a positive integer ID and a nonempty display_name. Return the trimmed label under label.
Test it with a request fixture that records its path and Accept header, then returns a fixed product. Print the product label and the recorded request. Finally call the client with a negative ID, catch the error and print its message and the total request count. That count proves invalid input was stopped before a request.
function createCatalogueClient(request) {
return {
async getProduct(id) {
if (!Number.isInteger(id) || id <= 0) {
throw new RangeError("Product ID must be a positive integer");
}
const response = await request("/products/" + id, {
method: "GET",
headers: new Headers({ Accept: "application/json" })
});
if (!response.ok) throw new Error("HTTP " + response.status);
const data = await response.json();
if (data === null || typeof data !== "object" || Array.isArray(data) ||
!Number.isInteger(data.id) || data.id <= 0 ||
typeof data.display_name !== "string" ||
data.display_name.trim() === "") {
throw new TypeError("Invalid product response");
}
return { id: data.id, label: data.display_name.trim() };
}
};
}
const calls = [];
const request = async (path, options) => {
calls.push(path + " " + options.headers.get("Accept"));
return new Response('{"id":7,"display_name":" Desk lamp "}', {
status: 200,
headers: { "Content-Type": "application/json" }
});
};
const client = createCatalogueClient(request);
console.log((await client.getProduct(7)).label);
console.log(calls.join(", "));
try {
await client.getProduct(-1);
} catch (error) {
console.log(error.message);
}
console.log("Request count:", calls.length);
// ✅ Expected output:
// Desk lamp
// /products/7 application/json
// Product ID must be a positive integer
// Request count: 1Extend the fixture one case at a time: a 404 response, a JSON null, an empty label and a rejected transport promise. Each should fail at its own boundary. Do not add a catch that returns a plausible product just to make the test green. This small client establishes a usable contract; deployment still needs the actual API’s authentication, response contract and failure policy.
References: MDN’s Fetch guide, Headers construction, and OWASP’s local storage guidance.
Practice quiz
What does this complete program print? const response = new Response("Missing", { status: 404 }); console.log(response.ok, response.status);
- false 404
- true 404
- false 200
- Constructing the response throws
Answer: false 404. The response exists, but its status is outside the successful 200–299 range.
What does this complete program print? const response = new Response('{"id":"7"}'); const data = await response.json(); console.log(typeof data.id);
- number
- string
- object
- undefined
Answer: string. JSON parsing preserves the quoted ID as a string; it does not validate or convert the API schema.
What does this complete program print? const options = { headers: { "X-Trace": "demo" } }; const request = { headers: { Accept: "application/json" }, ...options }; console.log(new Headers(request.headers).has("Accept"));
- true
- undefined
- false
- TypeError
Answer: false. The later headers property replaces the earlier object; object spread does not merge nested headers.
What does this complete program print? const supplied = new Headers({ "X-Trace": "demo" }); const copied = new Headers(supplied); copied.set("Accept", "application/json"); console.log(supplied.has("Accept"), copied.has("Accept"));
- true true
- false false
- true false
- false true
Answer: false true. The Headers constructor copies the supplied header entries; changing the copy does not mutate the original.
Which credential-storage rule belongs in a browser API client?
- Session tokens are sensitive; choose an authentication design deliberately rather than treating localStorage as a safe token store.
- Tokens are the only secrets that are always safe in localStorage.
- Changing a token’s key name prevents XSS from reading it.
- Every browser API should embed a private server key in its JavaScript.
Answer: Session tokens are sensitive; choose an authentication design deliberately rather than treating localStorage as a safe token store.. JavaScript can read localStorage in its origin. A wrapper does not turn that storage into a secure session boundary.
What does this complete program print? let calls = 0; async function read(id) { if (!Number.isInteger(id) || id <= 0) throw new RangeError("Bad ID"); calls += 1; } try { await read(-2); } catch (error) { console.log(error.message); } console.log(calls);
- Bad ID 1
- Bad ID 0
- 0 Bad ID
- RangeError is ignored
Answer: Bad ID 0. The ID check throws before the counter representing a request is incremented.
A POST request fails after it may have reached the server. What should the generic wrapper do?
- Retry forever until a response arrives.
- Retry every status because all failures mean no change was made.
- Use an explicit retry policy that accounts for the operation and server idempotency support.
- Return a made-up successful result.
Answer: Use an explicit retry policy that accounts for the operation and server idempotency support.. A missing response does not prove that the server did not perform the write. Retrying can duplicate an operation.
What does this complete program print? async function read(response) { if (!response.ok) throw new Error("HTTP " + response.status); return response.json(); } try { await read(new Response("<h1>Down</h1>", { status: 503 })); } catch (error) { console.log(error.message); }
- SyntaxError
- undefined
- <h1>Down</h1>
- HTTP 503
Answer: HTTP 503. The status guard rejects before JSON parsing, so the HTTP failure is preserved.
Continue this course
- Previous: Web Storage APIs (localStorage, sessionStorage, IndexedDB)
- Next: Error Handling Patterns in Large JS Apps — Centralise error handling with boundaries, loggers, and fallback strategies
- Quick reference: JavaScript cheat sheet