Vladislav
Vladislav

Reputation: 193

Postman - Pass local variable from Pre-request Script into the Body

I am relatively new to Postman. In Pre-request Script I defined variable: updatedUserGrTypeName,

var updatedUserGrTypeName = pm.environment.get("newGroupTypeToUpdateAndDelete") + 
"_PutUpdate";

enter image description here

Then I passed it into the Body:

{
  "id": {{grTypeIdUpdateDelete}},
  "name": "{{updatedUserGrTypeName}}"
}

enter image description here

Please, notice {{grTypeIdUpdateDelete}} defined in the Environment - it is Global variable.

I click Send.

And I would expect to get the record updated to be "NewIdentityGrTypeToBeUpdatedAndDeleted_PutUpdate" which is actually current value of the global variable "newGroupTypeToUpdateAndDelete" concatenated with "_PutUpdate" string.

However, actual result is: "{{updatedUserGrTypeName}}" (see the screenshot from the data base):

enter image description here

It seems to be that when I pass into the Body the name of the global variable (defined in the Environment) {{grTypeIdUpdateDelete}} it works (it does update the record by its id), however it does not pick up the value from the var grTypeIdUpdateDelete defined in Pre request.

Can somebody help me, please.

Upvotes: 1

Views: 11253

Answers (1)

mbj
mbj

Reputation: 1015

Postman variables and JavaScript variables are different things. To use a calculated value in a request, you need to store it in a Postman variable first.

Similar to how you used the get(key) method on pm.environment to read a Postman environment variable, you can also create or update Postman variables in the scope of your choice by using the set(key, value) on the corresponding variable collection.

For this particular case, you would probably store it as a "local" Postman variable to aviod adding clutter to your environment, by calling pm.variables.set("updatedUserGrTypeName", updatedUserGrTypeName). Your pre-request script would look like this:

var updatedUserGrTypeName = pm.environment.get("newGroupTypeToUpdateAndDelete")
 + "_PutUpdate";
pm.variables.set("updatedUserGrTypeName", updatedUserGrTypeName);

For more information, see "Defining variables in scripts" in the Postman Learning Center.

Upvotes: 3

Related Questions