Skip to curriculum
Jump to the editor

24.10. Build and parse API requests

Medium
Topics

This question is in

24. Build a small library
35–50 min

Two 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

JAVASCRIPT
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 match

Requirements

buildRequest

  1. method is upper-cased; it defaults to GET. With nothing else given, the result is { method, url, headers: {}, body: null }.
  2. Each :name in url (a name starts with a letter or _, then letters, digits or _) is replaced by params[name], encoded with encodeURIComponent. A value that is undefined, null or "" throws Missing path parameter: <name>. A value whose text is . or .. throws Invalid path parameter: <name>: URL parsing would treat it as a dot segment (/users/.. is /), and no encoding avoids that. A key of params that the url does not use throws Unknown path parameter: <name>.
  3. query is added with URLSearchParams: one pair per array item, undefined and null values left out, joined with ?, or & when the url already has a ?. A #hash in the url stays at the end, after the query (the query goes before the first #). An empty query adds nothing.
  4. Header names are lower-cased and values turned into strings.
  5. body, when it is not undefined (so 0, false and null count), is sent as JSON.stringify(body) with content-type: application/json. form is sent URL-encoded like a query string, with content-type: application/x-www-form-urlencoded. A content-type already in headers is kept.
  6. body and form together throw Use body or form, not both. A body or form on GET or HEAD throws <METHOD> requests cannot have a body.

parseRequest

  1. 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.
  2. 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, gives null.
  3. Each :name segment gives params[name], decoded with decodeURIComponent. A segment with broken % encoding throws Malformed path parameter: <name>. A pattern that uses a name twice throws Duplicate path parameter: <name>.
  4. query holds the query string's values as strings; a key that appears more than once gives an array of its values, in order.
  5. The body is read by the content-type header, whose name may be in any case: one that includes application/json is parsed with JSON.parse (an invalid one throws Invalid JSON body); one that includes application/x-www-form-urlencoded is read like a query string; any other body stays text. No body, or "", gives null.
  6. Every key, __proto__ included, is kept as an own property of params, query, a form body and the built headers.
  7. A request made by buildRequest parses back, against the same path with each :name as 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

JAVASCRIPT
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}' }
JAVASCRIPT
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"); // null
JAVASCRIPT
buildRequest({ 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 buildRequest and parseRequest from request.js. Nothing is sent: these functions only build and read plain objects.
  • URLSearchParams, URL, encodeURIComponent and decodeURIComponent are allowed. Wildcards in patterns, optional parameters, multipart/form-data and converting query strings back to numbers or booleans are out of scope.

Hints

  1. Why must a path parameter use encodeURIComponent, not encodeURI? Try a value with a / in it.
  2. if (body) and body !== undefined treat which values differently?
  3. 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
Back to the question
Loading the editor…