The rq.collectionVariables object provides methods to manage collection variables during script execution. Collection variables are scoped to a specific collection and are only accessible within the requests that belong to that collection. Unlike environment variables (scoped to a specific environment), collection variables persist across all environments within the same collection.
Methods
rq.collectionVariables.set(key, value)
Creates or updates a collection variable with the given key and value. If the variable already exists, it will be updated with the new value.
Parameters:
key (string): The name of the collection variable
value (any): The value to store (converted to a string). Passing null or undefined clears the variable — equivalent to unset(key), so a later get returns undefined (not the string "null").
Example:
rq.collectionVariables.get(key)
Retrieves the value of the specified collection variable.
Parameters:
key (string): The name of the collection variable to retrieve
Returns: The value of the collection variable, or undefined if it doesn’t exist.
Example:
rq.collectionVariables.unset(key)
Removes the specified collection variable.
Parameters:
key (string): The name of the collection variable to remove
Example:
rq.collectionVariables.clear()
Removes all variables from the current collection.
Parameters: none.
Example:
rq.collectionVariables.clear() works only when the request belongs to a collection. Calling it from a request that is not in a collection throws an error, the same as set() and unset().
Common Use Cases
Store API Base Path
Set a base path that all requests in the collection can use:
Then use it in your request URL:
Share Data Between Collection Requests
Pass data from one request to another within the same collection:
Store Default Values
Set default values that can be overridden by environment variables:
Track Collection State
Maintain state across requests in a collection:
Store Computed Values
Calculate and store values that multiple requests will use:
Best Practices
-
Naming Convention: Use clear, descriptive names that indicate the variable’s purpose
-
Initialize in Setup Requests: Create a setup or initialization request that sets default collection variables
-
Validate Before Use: Check if a variable exists before using it
-
Clean Up: Remove variables that are no longer needed
-
Document Variables: Add comments in your scripts explaining what each variable is for