Ivan Elianto
Ivan Elianto

Reputation: 442

How to change Postman current variable value in collection scope?

I have variable "TOKEN" in my collection scope. I try to set the value using Tests scripts when do a request. But the variable not changed.

So, I try to use environment scope variable. And It works.

Why It's doesn't work when in collection scope? I had read about postman variable scope here and understand it well.

Here're some screenshots:

1. First, I call login endpoint.

Call Login

Below is the console result. Nothing wrong.

Console Result

Until I try to get all users endpoint that required token in request header. The status is 401 because the token is null. If the token is not null, then it will return 200:

Get Users Endpoint

It's gracefully working when I add "TOKEN" variable to environment. Switch to No Environment again will result 401 status code:

Result

Upvotes: 6

Views: 6718

Answers (4)

Decypher
Decypher

Reputation: 700

You can now use:

pm.collectionVariables.set("variable_key", "variable_value");
  • In my original answer in June 2019, I wrote that collection variables are not editable through scripts, and can only be changed manually. As noted, this is no longer the case. . . .*

Upvotes: 1

Andrew Cressman
Andrew Cressman

Reputation: 46

This may be new since this question was posted, but for anyone else finding this, you can set collection variables using:

pm.collectionVariables.set(key, value)

See: https://learning.postman.com/docs/sending-requests/variables/#defining-variables-in-scripts

Upvotes: 3

Bohdan Ganicky
Bohdan Ganicky

Reputation: 159

It seems you can only set env variables when some environment is selected: https://learning.postman.com/docs/postman/scripts/postman-sandbox/#environment-and-global-variables

enter image description here

Upvotes: 0

K14
K14

Reputation: 191

Turn off Automatic persist variable values from postman settings.

image

Upvotes: 0

Related Questions