> For the complete documentation index, see [llms.txt](https://docs.thewalletcrew.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md).

# fetch

Reference for the global fetch function in scripts: options, body rules, errors, retries and idempotency, with links to authentication, cache and throttle.

`fetch` is the only way a script talks to another system over HTTP. It is a global function: no import is needed, and it is available in every script file and every handler. Scripts use it to enrich a pass from a CRM or ERP, to push a registration to a marketing platform, or to obtain a token. The function looks like the browser `fetch`, but it is not the same: most options are written in PascalCase, the result has only two members, and a failing status code throws by default. Authentication is on [fetch authentication](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.md), and the cache and the throttle are on [fetch cache and throttle](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-cache-and-throttle.md).

<details>

<summary><strong>Real-world examples</strong></summary>

* A pass data provider looks up a loyalty balance in a CRM, caches the answer for ten minutes and, when the CRM is down, leaves the pass untouched.
* A pipeline element creates or updates a contact in a marketing platform after a registration, authenticating with OAuth 2.0 client credentials.
* An email engine script posts a message to a marketing-automation endpoint that expects a form-encoded body.
* An install hook reports "installed" and "uninstalled" events to a data warehouse endpoint secured with a bearer token fetched from a custom login endpoint.

</details>

## Signature and result

```js
const result = await fetch(url, options);
// result: { StatusCode: number, ResponseText: string }
```

`fetch` returns a promise, so every call is awaited inside an `async` handler. The result has exactly two members, written with a capital first letter:

| Member         | Type   | Meaning                                                                           |
| -------------- | ------ | --------------------------------------------------------------------------------- |
| `StatusCode`   | number | The HTTP status code of the response, for example `200` or `404`.                 |
| `ResponseText` | string | The whole response body read as text. Empty string when the response has no body. |

Response headers are not exposed, and neither is binary content: the body is always read as text. A script that needs a value from a header cannot obtain it with `fetch`.

The second argument is optional. Calling `fetch(url)` sends a `GET` without a body and without authentication.

## Options and defaults

Option names are case-sensitive. An option with a misspelled name, such as `method` instead of `Method`, is ignored without any message, and the default applies. The top-level options and the members of `Cache` and `Throttle` are PascalCase, but the members of `Authentication` are camelCase:

| Where                                                            | Casing     | Examples                                                           |
| ---------------------------------------------------------------- | ---------- | ------------------------------------------------------------------ |
| Top-level options, members of `Cache` and `Throttle`, the result | PascalCase | `Method`, `ThrowOnError`, `CacheKey`, `PermitLimit`, `StatusCode`  |
| Members of `Authentication`                                      | camelCase  | `mode`, `userName`, `accessTokenUrl`, `tokenRetriever`, `cacheKey` |
| Value returned by a `CustomBearer` token retriever               | PascalCase | `Value`, `DurationInMilliseconds`, `ExpirationDate`                |

| Option           | Type                   | Default | Meaning                                                                                                                                                                                         |
| ---------------- | ---------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Method`         | string                 | `GET`   | The HTTP method: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, and so on.                                                                                                                            |
| `Headers`        | object (string values) | none    | Extra request headers. Applied after the `Authentication` option, so they are added on top of what the authentication mode sets.                                                                |
| `Body`           | object or string       | none    | The request body. See [Body rules](#body-rules).                                                                                                                                                |
| `Authentication` | object                 | none    | How the call authenticates. Always an object with a `mode` member. See [fetch authentication](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.md). |
| `ThrowOnError`   | boolean                | `true`  | When `true`, any response whose status is not 2xx throws. When `false`, the status and body are returned.                                                                                       |
| `Cache`          | object                 | none    | Keeps the result for a duration. See [fetch cache and throttle](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-cache-and-throttle.md#cache).                     |
| `Throttle`       | object                 | none    | Limits how many calls are made in a time window. See [fetch cache and throttle](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-cache-and-throttle.md#throttle).  |

The `Headers` values must be strings. A header named `Content-Type` also decides the content type of the body, as described below.

## Body rules

A body is meaningful for `POST`, `PUT` and `PATCH`. What is sent depends on the type of `Body` and on the `Content-Type` header.

| `Body`          | `Content-Type` header                                   | What is sent                                                                                |
| --------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| object or array | not set                                                 | The value serialized with `JSON.stringify`, content type `application/json; charset=utf-8`. |
| string          | not set                                                 | The string unchanged, content type `application/json; charset=utf-8`.                       |
| object or array | any other value, for example `application/vnd.api+json` | The value serialized as JSON, sent with the given content type.                             |
| string          | any other value, for example `text/xml` or `text/plain` | The string unchanged, sent with the given content type.                                     |
| object          | exactly `application/x-www-form-urlencoded`             | The members sent as form fields, each value converted to text.                              |
| string          | exactly `application/x-www-form-urlencoded`             | Not supported. A form body must be an object.                                               |

Two details matter in practice. The form mode is selected only when the `Content-Type` value is exactly `application/x-www-form-urlencoded`; a value that carries a charset, such as `application/x-www-form-urlencoded; charset=utf-8`, is treated as an ordinary content type, and the object is then sent as JSON. The header name itself is matched without regard to case. A string body is never re-encoded, so a script that builds JSON by hand must make sure that the string is valid JSON.

```js
// JSON body, default content type
await fetch("https://api.example.com/contacts", {
  Method: "POST",
  Body: { email: entity.email, language: entity.language }
});

// Form body: the object members become form fields
await fetch("https://api.example.com/subscribe", {
  Method: "POST",
  Headers: { "Content-Type": "application/x-www-form-urlencoded" },
  Body: { email: entity.email, list: "newsletter" }
});

// XML body: a string with its own content type
await fetch("https://api.example.com/soap", {
  Method: "POST",
  Headers: { "Content-Type": "text/xml; charset=utf-8" },
  Body: xmlString
});
```

## Errors and edge cases

### Default: a failing status throws

Because `ThrowOnError` defaults to `true`, a `404`, `401` or `500` response does not return: the call throws an `Error`. The message is the text produced by the platform for the status, for example `Response status code does not indicate success: 404 (Not Found).` The message contains the status only. It does not contain the response body, so a script that needs the error details sent by the remote system must use `ThrowOnError: false`.

What happens to an exception thrown by a handler depends on the endpoint: some propagate it to the user flow, others swallow it and log it. The behavior is described on each [endpoint page](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints.md). A handler that enriches optional data should therefore catch the error itself, so that a remote outage does not block a registration.

```js
try {
  const res = await fetch("https://api.example.com/profile/" + encodeURIComponent(entity.email));
  entity["crm.tier"] = JSON.parse(res.ResponseText).tier;
} catch (error) {
  console.warn("Profile lookup failed: " + error.message);
}
```

### ThrowOnError false: check the status

With `ThrowOnError: false` the call returns whatever the server answered, including `4xx` and `5xx`. The script then owns the decision. In a pass data provider, both cases return `false`: `true` means that data was found (see [Pass data provider](https://docs.thewalletcrew.io/developers-guides/scripting/endpoints/pass-data-provider.md#return-value)). A script must never parse `ResponseText` before checking `StatusCode`: an error page is usually HTML or empty, and `JSON.parse` on it throws a confusing error.

```js
const res = await fetch("https://api.example.com/profile/" + encodeURIComponent(entity.email), {
  ThrowOnError: false
});

if (res.StatusCode === 404) {
  return false;
}
if (res.StatusCode < 200 || res.StatusCode >= 300 || !res.ResponseText) {
  console.warn("Profile lookup answered " + res.StatusCode);
  return false;
}
const profile = JSON.parse(res.ResponseText);
```

### What ThrowOnError does not cover

`ThrowOnError: false` only concerns HTTP status codes. A call that cannot reach the remote system at all, for example because the host name does not resolve, the connection is refused, or the call times out, throws whatever the option value is. A resilient script therefore combines `ThrowOnError: false` with a `try`/`catch`. A call denied by a throttle with `ThrowOnDenied: true` throws as well, as described on [fetch cache and throttle](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-cache-and-throttle.md#throttle).

An invalid `Authentication` option throws too (see [fetch authentication](https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch/fetch-authentication.md)): a missing `mode` gives "'mode' attribute for authentication is missing", an unknown mode gives "Authentication mode 'x' is not supported", and a missing required member gives a message naming the member. A failing token request of the `OAuth2.0` mode throws as well, because it happens before the actual request is sent.

### Parsing the response

The body is a string. A JSON response is parsed in the script. An empty body must be handled before parsing, because `JSON.parse("")` throws.

```js
function parseJson(res) {
  if (!res.ResponseText) {
    return null;
  }
  try {
    return JSON.parse(res.ResponseText);
  } catch (error) {
    return null;
  }
}
```

For XML or CSV answers, the script parses the text itself. The `ResponseText` of a binary answer is not usable.

## Network behavior

The platform sends the call, and a few transport rules apply to every use of `fetch`.

* The destination must be a publicly reachable address. A call to an internal address is refused (a script that needs a private address cannot use `fetch`).
* Transient failures are retried automatically, up to three times with a growing, randomized delay: responses `5xx`, `408` and `429`, network errors and timeouts. Retries apply to every method, `POST` included.
* A single attempt is abandoned after 60 seconds, and the whole call, retries included, after about 100 seconds.
* Redirects are followed. Cookies are not kept between calls.
* The response body is read completely, as text.

A script runs inside the request or job that triggered it, so the total time of its calls counts for that request or job. Several chained calls with slow targets make registrations slow, which is one more reason to cache and to keep the number of calls small.

### Idempotency

Because a `POST` can be sent again when the first attempt fails after the remote system processed it, the target of a `POST` must tolerate duplicates. An endpoint that creates a record on each call produces duplicates. The robust patterns are to call an endpoint that is an upsert (create or update by a business key such as the email address), to send an idempotency key or a client-generated identifier that the remote system recognizes, or to check for the record first.

```js
await fetch("https://api.example.com/v1/contacts/" + encodeURIComponent(entity.email), {
  Method: "PUT",
  Body: { email: entity.email, firstName: entity.firstName }
});
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.thewalletcrew.io/developers-guides/scripting/globals/fetch.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
