request()
request calls an API and returns the same result shape whatever envelope the server uses.
const r = await request(url, method, options);
| Parameter | Description |
|---|---|
url | The 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 |
method | GET, POST, PUT, PATCH, or DELETE, in any case |
options | Optional. 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:
| Field | Description |
|---|---|
ok | true when the call succeeded, and false otherwise |
status | The HTTP status, or 0 when the call couldn't reach the server |
data | The envelope's data when there is one, and otherwise the whole body |
message | The server's message or error text, or null |
code | Only when ok is false: the reason; see Error codes and messages |
headers | The 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
GETwith abody - A bad option value
Options
request takes these options:
| Option | Default | What it does |
|---|---|---|
params | None | Adds query values; null is skipped, an array repeats the key, and an object is sent as JSON |
body | None | Sends a body with POST, PUT, PATCH, or DELETE as JSON; a FormData is sent as multipart |
files | None | Uploads 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]) |
token | None | Sends Authorization: Bearer <token>, or the token unchanged if it already starts with Bearer ; a blank token sends nothing |
headers | None | Overrides the headers that request sets; names are compared without case |
timeout | 15000 | Sets the timeout in milliseconds, in both languages |
retries | 2 for GET, 0 for other methods | Retries after a network error, a timeout, a 429, or a 5xx; other methods retry only when you set this, so nothing is saved twice |
retryDelay | 300 | Sets 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 |
transport | fetch in JavaScript, urllib in Python | Replaces 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.