Skip to main content
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):
const res = await rq.sendRequest("https://api.example.com/health");
console.log("Status:", res.code);
Callback style:
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

const res = await rq.sendRequest("https://api.example.com/users");
A bare string is sent as a GET request.

Configuration object

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

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.
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.
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") },
        ],
    },
});
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.

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:
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.
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:
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);
}
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.

Common Use Cases

Fetch a token before the main request

// 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

// 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

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