24.10. Build and parse API requests
Topics
This question is in
24. Build a small libraryTwo sides of every API call need the same rules. The client builds a request: it fills path parameters into /users/:id, encodes the query string, and turns a body into JSON or form data with the right content-type. A mock server, a service worker or a test parses it back: does the path match a route, what are the parameters, what does the body hold? Getting one encoding step wrong (a / inside a parameter, a space in the query, 0 taken as "no body") breaks the call in ways that are hard to see.
Write buildRequest(spec) and parseRequest(request, pattern) in request.js, so that one undoes the other.
Signature
function buildRequest({ method, url, params, query, headers, body, form })
// returns { method, url, headers, body } body: a string, or null
function parseRequest({ method, url, headers, body }, pattern)
// pattern: "/users/:id" or "GET /users/:id"
// returns { params, query, body }, or null when the route does not matchRequirements
buildRequest
methodis upper-cased; it defaults toGET. With nothing else given, the result is{ method, url, headers: {}, body: null }.- Each
:nameinurl(a name starts with a letter or_, then letters, digits or_) is replaced byparams[name], encoded withencodeURIComponent. A value that isundefined,nullor""throwsMissing path parameter: <name>. A value whose text is.or..throwsInvalid path parameter: <name>: URL parsing would treat it as a dot segment (/users/..is/), and no encoding avoids that. A key ofparamsthat the url does not use throwsUnknown path parameter: <name>. queryis added withURLSearchParams: one pair per array item,undefinedandnullvalues left out, joined with?, or&when the url already has a?. A#hashin the url stays at the end, after the query (the query goes before the first#). An empty query adds nothing.- Header names are lower-cased and values turned into strings.
body, when it is notundefined(so0,falseandnullcount), is sent asJSON.stringify(body)withcontent-type: application/json.formis sent URL-encoded like a query string, withcontent-type: application/x-www-form-urlencoded. Acontent-typealready inheadersis kept.bodyandformtogether throwUse body or form, not both. A body or form onGETorHEADthrows<METHOD> requests cannot have a body.
parseRequest
- A pattern is a path, optionally preceded by a method and a space. With a method, the request's method must be the same (ignoring case), otherwise the result is
null. Without one, any method matches. - The request's url may be a path or an absolute URL; only its path and query count (not the host or the
#hash). Paths are compared segment by segment, empty segments ignored (so a trailing slash does not matter). A different number of segments, or a literal segment that differs, givesnull. - Each
:namesegment givesparams[name], decoded withdecodeURIComponent. A segment with broken%encoding throwsMalformed path parameter: <name>. A pattern that uses a name twice throwsDuplicate path parameter: <name>. queryholds the query string's values as strings; a key that appears more than once gives an array of its values, in order.- The body is read by the
content-typeheader, whose name may be in any case: one that includesapplication/jsonis parsed withJSON.parse(an invalid one throwsInvalid JSON body); one that includesapplication/x-www-form-urlencodedis read like a query string; any other body stays text. No body, or"", givesnull. - Every key,
__proto__included, is kept as an own property ofparams,query, a form body and the builtheaders. - A request made by
buildRequestparses back, against the same path with each:nameas a whole segment, to its parameters (as strings), its query (as strings) and its body. This holds for what a browser actually does with the url (new URL), not only for the string.
Examples
buildRequest({
method: "post",
url: "/shops/:shop/orders",
params: { shop: "north & south" },
query: { draft: true, tag: ["a", "b"] },
body: { sku: "A1", qty: 2 },
});
// { method: "POST",
// url: "/shops/north%20%26%20south/orders?draft=true&tag=a&tag=b",
// headers: { "content-type": "application/json" },
// body: '{"sku":"A1","qty":2}' }parseRequest(
{ method: "GET", url: "https://api.test/users/7/posts?tag=a&tag=b&q=red+shoes", headers: {}, body: null },
"GET /users/:id/posts",
);
// { params: { id: "7" }, query: { tag: ["a", "b"], q: "red shoes" }, body: null }
parseRequest({ method: "GET", url: "/users/7" }, "/posts/:id"); // nullbuildRequest({ url: "/users/:id" }); // throws Error: Missing path parameter: id
buildRequest({ url: "/search", body: { q: "x" } }); // throws Error: GET requests cannot have a body
buildRequest({ method: "PUT", url: "/flag", body: false }).body; // "false"Environment
- Plain JavaScript in a browser page; the tests call the globals
buildRequestandparseRequestfromrequest.js. Nothing is sent: these functions only build and read plain objects. URLSearchParams,URL,encodeURIComponentanddecodeURIComponentare allowed. Wildcards in patterns, optional parameters,multipart/form-dataand converting query strings back to numbers or booleans are out of scope.
Hints
- Why must a path parameter use
encodeURIComponent, notencodeURI? Try a value with a/in it. if (body)andbody !== undefinedtreat which values differently?- When you read a query string, how do you know whether a key's value should be a string or an array?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it