Skip to main content

request()

request calls an API and returns the same result shape whatever envelope the server uses.

const r = await request(url, method, options);
ParameterDescription
urlThe address to call; in the browser it can be relative to the page, such as /api/v1/x, and in Node and Python it must be the full URL
methodGET, POST, PUT, PATCH, or DELETE, in any case
optionsOptional. The options for the call

In JavaScript, request returns a promise. In Python, it returns the result directly.

Result​

The result has the same shape whether the server answers { success, data }, { status: "success", data }, or a bare value:

{ ok: true,  status: 200, data, message, headers }
{ ok: false, status: 400, code, message, data, headers }

The result has these fields:

FieldDescription
oktrue when the call succeeded, and false otherwise
statusThe HTTP status, or 0 when the call couldn't reach the server
dataThe envelope's data when there is one, and otherwise the whole body
messageThe server's message or error text, or null
codeOnly when ok is false: the reason; see Error codes and messages
headersThe response headers

A 4xx or 5xx response is a result with ok: false, not an exception.

Throws​

request throws an error only for a wrong call:

  • An unknown method or option
  • A GET with a body
  • A bad option value

Options​

request takes these options:

OptionDefaultWhat it does
paramsNoneAdds query values; null is skipped, an array repeats the key, and an object is sent as JSON
bodyNoneSends a body with POST, PUT, PATCH, or DELETE as JSON; a FormData is sent as multipart
filesNoneUploads files as multipart, with body's fields beside them; in JavaScript, a File or Blob; in Python, bytes, an open file, or (filename, bytes[, content_type])
tokenNoneSends Authorization: Bearer <token>, or the token unchanged if it already starts with Bearer ; a blank token sends nothing
headersNoneOverrides the headers that request sets; names are compared without case
timeout15000Sets the timeout in milliseconds, in both languages
retries2 for GET, 0 for other methodsRetries after a network error, a timeout, a 429, or a 5xx; other methods retry only when you set this, so nothing is saved twice
retryDelay300Sets the first wait in milliseconds, which doubles on each retry
responseType"json"Reads the response as "json", "text", or "blob" for downloads; in Python, "blob" returns bytes in data
transportfetch in JavaScript, urllib in PythonReplaces the HTTP layer, so tests need no network or server

JavaScript uses fetch, which browsers and Node 18 or later provide. Python uses urllib. Neither adds a dependency.