Setting/getting collection variable value in script

I have a collection variable defined (Collection > Edit > Variables tab. Variable name: token) that I’m using in as request header value. I want to set its value in script. I’m trying to set it with this:

pm.variables.set(“token”, jsonData.access_token);

but the Collection variable value doesn’t change. In the past I’ve used pm.globals and pm.environment, and those work here as expected, but this variable is actually scoped to the collection. I’d rather work with it within that scope than use the broader globals or environment scope.

@CBoland First of all, welcome to the community, thanks for coming to ask a good question like this.
When it comes to Collection Variables they are treated a bit differently than Environment and Global variable.
https://learning.getpostman.com/docs/postman/environments_and_globals/variables#defining-collection-variables

Hopefully this will help you out a bit. If the variable is not static, and I assume thats the case if its a token. You will likely need to scope this as an environment variable, you can also unset it at the end of the tests if need be.

Hopefully this helps.

1 Like

Yes, @tmccann, that helps. It appears then that Collection variables are static whereas Environment and Global variables are dynamic. Perhaps the documentation could be clarified to this effect? Another option is to make Collection variables dynamic (and consistent) with Environment and Globals.