3
votes

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

4
Please add the code you're using and some screen shots, to help explain what you're doing. Currently, it says "I have this thing I'm not showing you and I have this code doing something you can't see" :) You need to provide more context for people to help. - Danny Dainton
Okay, I had add it recently. @DannyDainton - Ivan Elianto
Are you trying to programmatically set the variable at the collection level? You will only be able to read or get those and not write or set them. - Danny Dainton
@DannyDainton Okay. I think it's good to explain in postman's page about this. - Ivan Elianto
Does this answer your question? Accessing Collection Variables in Postman - Henke

4 Answers

2
votes

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

1
votes

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. . . .*
0
votes

Turn off Automatic persist variable values from postman settings.

image