Scripts

Reading and writing variables in scripts

Read variables and set new values from pre-request and post-response scripts.

Overview

Scripts can read every variable a request can use, and set values that the request, later requests or later scripts pick up. A common use is to save a token or an ID from one response and send it with the next request.

Each variable scope has an object with the same methods, get, set, has, unset, clear, toObject and replaceIn:

ObjectVariables
relay.variablesEvery scope, in precedence order, plus values set for this send.
relay.environmentThe workspace's active environment.
relay.collectionVariablesThe request's collection.
relay.workspaceVariablesThe workspace's default variables.
relay.globalsGlobal variables, shared by every workspace.

pm.environment, pm.collectionVariables, pm.globals and pm.variables are the same objects.

Read a variable

To read a variable the way the request would see it, use relay.variables.get(). It looks through values set for this send, then the request's folders from the innermost, the active environment, the collection, the workspace and globals, and returns the first value it finds.

const baseUrl = relay.variables.get("baseUrl");

To read from one scope only, use that scope's object:

const token = relay.environment.get("token");
if (!relay.collectionVariables.has("apiVersion")) {
  console.warn("Set apiVersion on the collection.");
}

get() returns the value as it's written, so a value that contains {{name}} tokens comes back with the tokens in it. To expand them, pass the text to replaceIn():

const url = relay.variables.replaceIn("{{baseUrl}}/users/{{userId}}");

replaceIn() also generates dynamic variables such as {{$guid}} and {{$randomEmail}}, with a new value each time.

Set a value for this send

relay.variables.set() sets a value that lasts until the send ends. It takes precedence over every scope, so the request's {{name}} tokens use it, and post-response scripts can read it.

// Pre-request script: use {{timestamp}} in the request's headers or body.
relay.variables.set("timestamp", String(Date.now()));

Values set this way aren't saved, which makes them a good fit for values that only make sense for one send, such as a signature or a timestamp.

Save a value for later requests

To keep a value after the send, set it in a scope. Relay saves the change to the workspace, as if you'd edited the variable yourself.

// Post-response script
const { id } = relay.response.json();
relay.environment.set("orderId", id);

set() updates the variable if the scope has one with that name, keeping its description and whether it's secret, or adds a new one. A value set on a secret variable stays on your Mac. Variables hold text, so a number is saved as its text and an object as JSON:

relay.environment.set("lastOrder", { id, total: 42.5 });
const order = JSON.parse(relay.environment.get("lastOrder"));

A pre-request script's changes are saved before Relay resolves the request's variables, so the request uses the new values right away.

If a scope doesn't exist for the request, nothing is saved and Relay writes a warning to the Console in the Tests tab. This happens when you set an environment variable while no environment is active, or a collection variable from a draft.

Scripts can read folder variables through relay.variables, but can't set them.

Remove values

unset() removes a variable from a scope, and clear() removes all of a scope's variables:

relay.environment.unset("token");
relay.variables.clear(); // Values set for this send only.

You can't undo a value a script sets or removes, because it happens as part of a send. You can undo a clear() on a scope with Edit > Undo.

Pass a token from a login request to other requests

A typical API hands out a token when you log in and expects it on every other request. With a short script, you log in once and every request picks up the token.

  1. Create a request called Log In that posts your credentials, such as POST {{baseUrl}}/auth/login.

  2. Add a post-response script to Log In that saves the token to the environment:

    test("Logged in", () => {
      relay.response.to.have.status(200);
    });
    
    const { access_token, expires_in } = relay.response.json();
    relay.environment.set("token", access_token);
    relay.environment.set("tokenExpiresAt", String(Date.now() + expires_in * 1000));
  3. In the sidebar, Control-click the collection and choose Edit Auth…. Choose Bearer Token and enter {{token}} as the token, so every request in the collection sends it.

  4. Send Log In, then send any other request in the collection.

To renew the token without sending Log In by hand, give the collection a pre-request script that logs in when the token is missing or about to expire:

// Collection pre-request script
const expiresAt = Number(relay.environment.get("tokenExpiresAt") ?? 0);

if (relay.info.requestName !== "Log In" && Date.now() > expiresAt - 60000) {
  const response = await relay.sendRequest({
    url: relay.variables.replaceIn("{{baseUrl}}/auth/login"),
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
      mode: "raw",
      raw: JSON.stringify({
        username: relay.environment.get("username"),
        password: relay.environment.get("password")
      })
    }
  });
  const { access_token, expires_in } = response.json();
  relay.environment.set("token", access_token);
  relay.environment.set("tokenExpiresAt", String(Date.now() + expires_in * 1000));
}

Mark password and token as secret in the environment so their values stay on your Mac.

See Also