> ## 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.request (Request object)

> Complete reference for the rq.request object in Requestly scripts, including properties and methods to access.

The `rq.request` object provides access to all details of the API request in your Requestly scripts. You can use these properties and methods in both pre-request and post-response scripts to read  data.

## Properties and Methods

### `rq.request.method`

Use this property to get the Request's method. The HTTP method of the request (e.g. `GET`, `POST`, `PUT`, `OPTION`, `DELETE`, `PATCH`, `HEAD`).

**Example:**

```jsx theme={null}
console.log("Request Method: ", rq.request.method);
```

### `rq.request.headers`

An object that holds the request headers. Read them with `rq.request.headers.get(name)`, `rq.request.headers.has(name)`, or `rq.request.headers.all()`, which returns a plain `{ name: value }` object. `JSON.stringify(rq.request.headers)` returns `{}` because the object exposes only methods (which `JSON.stringify` omits), so use `.all()` when you want to serialize the headers.

**Example:**

```jsx theme={null}
console.log("Headers: ", JSON.stringify(rq.request.headers.all()));
```

You can also modify request headers from a **pre-request script**. The methods below change the headers that are sent with the request. Use them in pre-request scripts; in post-response scripts the request has already been sent, so header changes have no effect. Header changes apply to HTTP and GraphQL requests.

#### `rq.request.headers.add(header)`

Adds a header. If a header with the same name already exists, this adds a second one (it does not replace the existing header).

**Parameters:**

* `header` (object): `{ key, value }` - the header name and value.

**Example:**

```jsx theme={null}
rq.request.headers.add({ key: "X-Trace-Id", value: "abc-123" });
```

#### `rq.request.headers.upsert(header)`

Adds a header, or replaces it if a header with the same name already exists. Header names are matched case-insensitively.

**Parameters:**

* `header` (object): `{ key, value }` - the header name and value.

**Example:**

```jsx theme={null}
rq.request.headers.upsert({ key: "Authorization", value: "Bearer " + rq.environment.get("authToken") });
```

#### `rq.request.headers.remove(name)`

Removes every header with the given name (case-insensitive).

**Parameters:**

* `name` (string): The header name to remove.

**Example:**

```jsx theme={null}
rq.request.headers.remove("X-Debug");
```

#### `rq.request.headers.clear()`

Removes all request headers.

**Parameters:** none. Any argument passed is ignored. `clear()` always removes every header, so to remove a single header use `remove(name)` instead.

**Example:**

```jsx theme={null}
rq.request.headers.clear();
```

<Note>
  The same operations are available directly on `rq.request` as `rq.request.addHeader({ key, value })`, `rq.request.upsertHeader({ key, value })`, and `rq.request.removeHeader(name)`.
</Note>

### `rq.request.body`

The body of the request, accessible as a string. It is always a string, or `undefined` when the request has no body.

**Example:**

```jsx theme={null}
console.log("Body:", JSON.stringify(rq.request.body));
```

### `rq.request.url`

The request URL as a `Url` object, the same shape as Postman's `pm.request.url`. It converts to a string wherever one is expected (`"Sending to " + rq.request.url`, `` `${rq.request.url}` ``, `new URL(String(rq.request.url))`), and exposes the URL's parts:

| Property / method    | Value for `https://api.example.com:8443/v1/users/42?page=2&tag=a#top` |
| -------------------- | --------------------------------------------------------------------- |
| `protocol`           | `"https"`                                                             |
| `host`               | `["api", "example", "com"]`                                           |
| `port`               | `"8443"`                                                              |
| `path`               | `["v1", "users", "42"]`                                               |
| `hash`               | `"top"`                                                               |
| `query`              | a list of query parameters — see below                                |
| `variables`          | the request's path variables (`variables.get("id")`)                  |
| `getHost()`          | `"api.example.com"`                                                   |
| `getPath()`          | `"/v1/users/42"`                                                      |
| `getQueryString()`   | `"page=2&tag=a"`                                                      |
| `getPathWithQuery()` | `"/v1/users/42?page=2&tag=a"`                                         |
| `getRemote()`        | `"api.example.com:8443"`                                              |
| `toString()`         | the full URL                                                          |

**Example:**

```jsx theme={null}
if (rq.request.url.path.includes("healthz") || rq.request.url.host.includes("localhost")) {
    console.log("Skipping auth for", rq.request.url.toString());
}
```

`rq.request.url.query` is a list of query parameters with the same API as Postman's:

* Read: `get(name)`, `has(name)`, `one(name)`, `count()`, `idx(i)`, `indexOf(...)`, `all()`, `each(fn)`, `map(fn)`, `filter(fn)`, `find(fn)`, `reduce(fn, initial)`, `toString()`. `toObject()` returns `{ name: value }`; a repeated name becomes an array of values.
* Change: `add(param)`, `insert(param, before)`, `insertAfter(param, after)`, `prepend(param)`, `append(param)`, `upsert(param)`, `remove(name | fn)`, `clear()`, `populate(list)`, `repopulate(list)`, `assimilate(list, prune)`. A param is `{ key, value }` or a `"key=value"` string. `rq.request.url.addQueryParams(...)` and `removeQueryParams(...)` do the same in bulk.

`rq.request.url.variables` is the list of the request's path variables (`:id` in the URL) with the same list API, plus `replace("{{id}}")`, `substitute(object)`, `syncFromObject(object)`, `syncToObject()`.

You can also edit the URL parts directly: `rq.request.url.path.push("v2")`, `rq.request.url.host = ["api", "example", "com"]`, `rq.request.url.port = "8443"`, or `rq.request.url.update("https://...")` to replace the whole URL.

In a **pre-request script** every one of these changes applies to the request that is sent, as in Postman. In a post-response script the request has already been sent.

```jsx theme={null}
rq.request.url.query.add({ key: "trace-id", value: rq.variables.replaceIn("{{$guid}}") });
rq.request.url.path.push("v2");
console.log(rq.request.url.toString());
```

`JSON.stringify(rq.request.url)` returns the URL's parts, the same shape Postman uses: `{ protocol, host: [...], port, path: [...], hash, query: [{ key, value }], variable: [...] }`. Use `rq.request.url.toString()` when you want the URL as a string.

<Note>
  `rq.request.url` is an object, not a string, exactly as in Postman. `typeof rq.request.url` is `"object"`, a strict comparison such as `rq.request.url === "https://..."` is false, and string methods like `.split()` or `.includes()` are not available on it. Call `rq.request.url.toString()` first: `rq.request.url.toString().split("?")`, `rq.expect(rq.request.url.toString()).to.equal(...)`. Scripts written before this change that called a string method directly on `rq.request.url` need that one edit.
</Note>

### `rq.request.queryParams`

A read-only object mapping each query parameter name to its value (`{ name: value }`). Iterate it with `Object.entries()`.

**Example:**

```jsx theme={null}
console.log("Query Params:", JSON.stringify(rq.request.queryParams));
```

## Common Use Cases

### Logging Request Details

```jsx theme={null}
console.log("Making " + rq.request.method + " request to " + rq.request.url);
console.log("Request headers:", JSON.stringify(rq.request.headers.all()));
console.log("Request body:", JSON.stringify(rq.request.body));
```

### Conditional Logic Based on Request Method

```jsx theme={null}
if (rq.request.method === "POST" || rq.request.method === "PUT") {
    console.log("Sending data:", rq.request.body);
}
```

### Accessing Query Parameters

```jsx theme={null}
Object.entries(rq.request.queryParams).forEach(([key, value]) => {
    console.log(`Query param ${key}: ${value}`);
});
```

### Adding an Authentication Header

```jsx theme={null}
// In a pre-request script
const token = rq.environment.get("authToken");
if (token) {
    rq.request.headers.upsert({ key: "Authorization", value: "Bearer " + token });
}
```

## Related Documentation

* [Pre-request & Post-response Scripts](/api-client/scripts)
* [rq.sendRequest Object](/api-client/rq-api-reference/rq-send-request)
* [rq.execution Object](/api-client/rq-api-reference/rq-execution)
* [rq.response Object](/api-client/rq-api-reference/rq-response)
* [rq.environment Object](/api-client/rq-api-reference/rq-environment)
* [rq.collectionVariables Object](/api-client/rq-api-reference/rq-collection-variables)
* [rq.globals Object](/api-client/rq-api-reference/rq-globals)
* [rq.vault Object](/api-client/rq-api-reference/rq-vault)
* [rq.test Object](/api-client/rq-api-reference/rq-test)
* [rq.expect Object](/api-client/rq-api-reference/rq-expect)
