How to share a variable between requests in a folder in API Spector

Roy de Kleijn Roy de Kleijn · · 3 min read
How to share a variable between requests in a folder in API Spector

A common pattern is one request that produces a value the next request needs: a "Create" request returns an id, and a "Retrieve" request looks it up. You can pass that id through an environment or collection variable, but then its name has to be unique across the whole workspace. Folder variables keep it scoped to the folder, so two folders can both use orderId without clashing.

The folder scope

Scripts get a folder variable scope, sp.folder, alongside sp.environment, sp.collectionVariables, and sp.globals. It reads and writes:

sp.folder.get("petId")        // read
sp.folder.set("petId", "99")  // create or update
sp.folder.clear("petId")      // remove

A folder can also define starting values in its Variables, which sp.folder reads and {{petId}} interpolates like any other variable.

Create in one request, read in the next

When you run a folder or a collection, a value a script writes with sp.folder.set is visible to the later requests in the same folder. So a "Create pet" request saves the new id in its post response script:

sp.folder.set("petId", String(sp.response.json().id));

and a "Get pet" request later in the folder uses it, either as {{petId}} in the URL or with sp.folder.get("petId") in a script. No environment variable, no unique naming, no leaking the value to unrelated folders.

Scoping and precedence

Folder variables follow the folder tree. An inner folder's value overrides an outer folder's, so a nested group can refine a value without touching its parent. In the overall order, a folder variable overrides a collection variable, and an environment or local (session) value overrides the folder. That means a folder variable is a good default that a specific environment can still override.

Runner and CLI

The sharing happens during a run, so it works the same whether you run the folder from the app's Runner or from the command line in CI. A folder that sets up its own state and reads it back stays self contained, which is exactly what you want when the folder is one resource's worth of requests.

Why it helps

Chaining requests used to mean promoting every shared value to an environment or collection variable and hoping the names did not collide. A folder variable lives where the requests live, reads and writes from a script, and is seen only by its folder, so a folder of requests for one resource can carry its own ids and tokens without spilling into the rest of the workspace.

Try it in API Spector

Free and open source. No account needed to use the app.

Keep reading