Home > Blockchain >  Setting Postman env variable based on the repsonse where certain criteria is met
Setting Postman env variable based on the repsonse where certain criteria is met

Time:11-07

When I get a response in Postman, I want to be able to set an environment variable (using

pm.environment.set("variable_key", "variable_value");

when a condition is met from the response array.

So the requirements:

  • set an environment variable named idForAbc to the value of someArray.id where someArray.criteria = "ABC" (so idForAbc = 1)

  • set an environment variable named idForXyz to the value of someArray.id where someArray.criteria = "XYZ" (so idForXyz = 2)

Here is my sample response:

Example Response

CodePudding user response:

You can choose one of 2 ways:

const res = pm.response.json();

const abc = res.someArray.find(e => e.criteria === "ABC");
if(abc){
    pm.environment.set(`idFor${abc.criteria}`,abc.id)
}

const xyz = res.someArray.find(e => e.criteria === "XYZ");
if(xyz){
    pm.environment.set(`idFor${xyz.criteria}`,xyz.id)
}

or

const res = pm.response.json();

function saveVarByCriteria(arr, value){
    const obj = arr.find(e => e.criteria === value);
    if(obj){
        pm.environment.set(`idFor${obj.criteria}`, obj.id)
    }
}

saveVarByCriteria(res.someArray, "ABC");
saveVarByCriteria(res.someArray, "XYZ");
  • Related