> ## Documentation Index
> Fetch the complete documentation index at: https://docs.requestly.com/llms.txt
> Use this file to discover all available pages before exploring further.

# rq.sendRequest (Send a request)

> Reference for rq.sendRequest in Requestly scripts: send an HTTP request from a pre-request or post-response script and read the response.

The `rq.sendRequest` method lets you send an HTTP request from inside a script and read its response. Use it to fetch a token before the main request runs, call a second endpoint after a response arrives, or poll a status URL. It is available in both pre-request and post-response scripts.

## Calling rq.sendRequest

You can call `rq.sendRequest` in two styles. Both send the same request.

**Promise style (recommended):**

```jsx theme={null}
const res = await rq.sendRequest("https://api.example.com/health");
console.log("Status:", res.code);
```

**Callback style:**

```jsx theme={null}
rq.sendRequest("https://api.example.com/health", (err, res) => {
    if (err) {
        console.error("Request failed:", err);
        return;
    }
    console.log("Status:", res.code);
});
```

The callback follows the Node convention: the first argument is the error (or `null` on success), the second is the response.

## Request input

The first argument is either a URL string or a request configuration object.

### URL string

```jsx theme={null}
const res = await rq.sendRequest("https://api.example.com/users");
```

A bare string is sent as a `GET` request.

### Configuration object

```jsx theme={null}
const res = await rq.sendRequest({
    url: "https://api.example.com/users",
    method: "POST",
    header: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + rq.environment.get("authToken"),
    },
    body: {
        mode: "raw",
        raw: JSON.stringify({ name: "Ada" }),
    },
});
```

**Fields:**

* `url` (string, required): The request URL.
* `method` (string, optional): The HTTP method. Defaults to `GET`.
* `header` (object or array, optional): Request headers. Use a plain object (`{ "Header-Name": "value" }`) or an array of rows (`[{ key, value, disabled }]`). The field name is `header`, singular.
* `body` (object, optional): The request body. See [Body modes](#body-modes).

## Body modes

The `body` object has a `mode` that selects how the body is sent. Two modes are supported.

### Raw

Sends the body exactly as you provide it. Set the `Content-Type` header yourself.

```jsx theme={null}
const res = await rq.sendRequest({
    url: "https://api.example.com/users",
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
        mode: "raw",
        raw: JSON.stringify({ name: "Ada", role: "admin" }),
    },
});
```

### URL-encoded

Sends form fields as `application/x-www-form-urlencoded`. Requestly sets that `Content-Type` for you unless you set one yourself. Rows marked `disabled: true` are skipped.

```jsx theme={null}
const res = await rq.sendRequest({
    url: "https://api.example.com/login",
    method: "POST",
    body: {
        mode: "urlencoded",
        urlencoded: [
            { key: "username", value: "ada" },
            { key: "password", value: rq.environment.get("password") },
        ],
    },
});
```

<Note>
  Multipart form-data and file-upload bodies are not supported by `rq.sendRequest`. Scripts run in a sandbox with no access to your file system, so a body cannot read a file from disk.
</Note>

## Response

The response object passed to your callback (and resolved by the promise) has these members:

* `code` (number): The numeric HTTP status, for example `200`.
* `status` (string): The HTTP status text, for example `"OK"`.
* `headers`: The response headers. Read one with `headers.get("content-type")` (case-insensitive) or `headers["content-type"]`.
* `responseTime` (number): The round-trip time in milliseconds.
* `json()`: Parses the response body as JSON and returns it. Throws if the body is not valid JSON.
* `text()`: Returns the raw response body as a string.

**Example:**

```jsx theme={null}
const res = await rq.sendRequest("https://api.example.com/users/1");

console.log("Status:", res.code, res.status);
console.log("Content-Type:", res.headers.get("content-type"));
console.log("Took:", res.responseTime, "ms");

const user = res.json();
console.log("User name:", user.name);
```

## Error handling

An error is reported two ways at once: the promise rejects, and the callback receives it as the first argument. Handle whichever style you are using.

```jsx theme={null}
try {
    const res = await rq.sendRequest("https://does-not-resolve.example");
    console.log(res.code);
} catch (err) {
    console.error("Could not send the request:", err);
}
```

Two situations produce an error:

* **Invalid arguments:** the configuration has no usable `url`. The request is never sent.
* **Network error:** the request could not reach the server (for example DNS failure, connection refused, or a TLS problem).

An HTTP error status such as `404` or `500` is **not** treated as an error. The promise resolves and the callback receives the response normally. Inspect `res.code` to decide how to handle the status:

```jsx theme={null}
const res = await rq.sendRequest("https://api.example.com/users/999");
if (res.code === 404) {
    console.log("User not found");
} else if (res.code >= 500) {
    console.error("Server error:", res.code);
}
```

<Note>
  Always `await` the promise or attach a `.catch()` (or pass a callback). A request that is never awaited may have its error go unreported if the script finishes first.
</Note>

## Common Use Cases

### Fetch a token before the main request

```jsx theme={null}
// Pre-request script
const res = await rq.sendRequest({
    url: "https://api.example.com/auth/login",
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
        mode: "raw",
        raw: JSON.stringify({ user: "ada", pass: rq.environment.get("password") }),
    },
});

const token = res.json().accessToken;
rq.environment.set("authToken", token);
```

### Call a second endpoint after the response

```jsx theme={null}
// Post-response script
const created = rq.response.json();
const res = await rq.sendRequest("https://api.example.com/audit/" + created.id);
console.log("Audit record:", res.json());
```

### Read a response header

```jsx theme={null}
const res = await rq.sendRequest("https://api.example.com/data");
const rateLimit = res.headers.get("x-ratelimit-remaining");
console.log("Requests remaining:", rateLimit);
```

## Related Documentation

* [Pre-request & Post-response Scripts](/api-client/scripts)
* [Scripts Reference Overview](/api-client/rq-api-reference/overview)
* [rq.execution Object](/api-client/rq-api-reference/rq-execution)
* [rq.request Object](/api-client/rq-api-reference/rq-request)
* [rq.response Object](/api-client/rq-api-reference/rq-response)
* [rq.environment Object](/api-client/rq-api-reference/rq-environment)
