4

I have an API named getcampaignlist. It returns me all campaign list with descriptions according to relevant person. Like in image I have multiple campaign with id and description. I want to set environment variable using

"postman.setEnvironmentVariable("cmid", jsonData.id);" or

"postman.setEnvironmentVariable("cmid", jsonData.id) where jsonData.campaignName==="online Games "; "

For clarification check image

I mean I want to use all these id's in loop through collection runner. how can I set values in environment variable. Because when I set jsonData.id it can't decide which id value should be set in environment variable "cmid" and return false.

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
Muneeb Akhtar
  • 87
  • 3
  • 11
  • What do you mean by "return false"? Do you have `var jsonData = pm.response.json()` in the test tab where you have your `postman.setEnvironmentVariable("cmid", jsonData.id)` code? Also, this wouldn't get anything as it's an array so `jsonData[0].id` would get the first `id` in the list. – Danny Dainton Dec 28 '17 at 10:17

2 Answers2

2

This code can be added to the Tests tab to iterate over the response data (similar to your example) and assign the ID that matches Online Games as an environment variable. This can be referenced in another request by using the {{cmid}} in the URL.

const result = pm.response.json()

for (var i = 0; i < result.length; ++i)
     if (result[i].campaignName === "Online Games") {
         pm.environment.set('cmid', result[i].id)
     }

Example using Postman:

API Response

Danny Dainton
  • 23,069
  • 6
  • 67
  • 80
1

For the collection runner, you would normally use data files (csv or json), and access the variables with data, for example data.id.

Suzana
  • 4,251
  • 2
  • 28
  • 52