Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postman programmatically set collection variables in pre-request script

Tags:

Currently, it is possible to set and get variables from the global and environment scope, as well as the generic variable in a pre-request script. However, the documentation is not clear if it is possible to programmaticaly set collection scoped variables.

For example

pm.environment.set("timestamp", timestamp);  //acceptable pm.global.set("signature", hash);  //acceptable pm.variable.set("signature", hash); //acceptable pm.collection.set("signature", hash); //not possible? 

Is this possible?

like image 878
dmorrow Avatar asked Mar 07 '18 18:03

dmorrow


People also ask

Can we add new variables using pre script in Postman?

You can use pre-request scripts in Postman to execute JavaScript before a request runs. By including code in the Pre-request Script tab for a request, collection, or folder, you can carry out pre-processing such as setting variable values, parameters, headers, and body data.

How do I create a dynamic variable in Postman?

' In the request URL section, a dynamic variable should be written in {{__}} format. Let's say you have to pass an integer number from 1 to 1000, so for that, you need to add {{$randomInt}}. Like the above example of the number variable, Postman supports so many other dynamic variables as well.


1 Answers

You can only currently set these manually at the Collection level but you can reference these using the pm.variables.get('var_name') syntax.

https://www.getpostman.com/docs/v6/postman/environments_and_globals/variables#defining-collection-variables

EDIT:

Postman now allows you to use:

pm.collectionVariables.set('var_name', 'var_value') and pm.collectionVariables.get('var_name') to interact with the Variables at the Collection level.

https://stackoverflow.com/a/58325002/6028443

like image 153
Danny Dainton Avatar answered Oct 08 '22 01:10

Danny Dainton