How to get a collection of values from a response into another request as a variable?

Hi All,

I am new to postman and trying to get below collection which is part of a response into another collection variable to be used in another request.

“data”: [
{
“id”: 77
},
{
“id”: 76
},
{
“id”: 74
},
{
“id”: 73
}
]

How do I create a collection variable called “data” and store below which I can reuse as a data payload in another request?

Any help/pointers will be much appreciated. thanks

[
{
“id”: 77
},
{
“id”: 76
},
{
“id”: 74
},
{
“id”: 73
}
]

Hi @mk0681! Welcome to the community :wave:

If I understand your query correctly, you are wanting to set “data” (that is a response of one request) as a collection variable and then pass it to another request in the same collection, is that correct?

If so, you can do something like:

data = pm.response.json().data // get "data" property from response object
pm.collectionVariables.set('data', data) // set as a collection var named 'data'

Then you can access the ‘data’ variable by {{data}} or pm.collectionVariables.get('data') if in scripts.

For details about how to use collection variables in scripts, please refer to:

Hope this helps!
Let me know if you have further questions :slightly_smiling_face:

@mk0681 Welcome to the community!! :bouquet:

So just to add on what @taehoshino said, you need to stringify before storing it in a variable :slight_smile:

Please try the below snippet:

const dataresult = pm.response.json().data;

pm.collectionVariables.set("data", JSON.stringify(dataresult));
1 Like

Hi @bpricilla and @taehoshino , appreciate your quick response.
I copied this code under Test section of the request that generates JSON response:

const dataresult = pm.response.json().data;

pm.collectionVariables.set(“data”,JSON.stringify(dataresult));

and copied {{data}} under body section of the request that takes data as an input but I get an error in the 2nd request. data as an input is not recognized.
{“responseStatus”:“FAILURE”,“errors”:[{“type”:“INVALID_DATA”,“message”:“Invalid request body content”}]}
Any thoughts why that might be happening wrong?
Also I dont see any value inside data variable under environment.

Thanks

Hello @mk0681

You should be seeing the collection variable values here, we did as the collection variable and not environment variable.

Also can you possibly share the screenshot and some more details?

Because the body format should be as “JSON” for this kind, and your API should be hopefully can handle this.

Next Steps:

  1. Please check the collection variable if the value is stored properly.
  2. Ensure you are passing the body as “JSON” format.

If still not working, please post us with more details.

Thanks @bpricilla , I was able to get this working.
really appreciate your help in resolving the problem.

1 Like

@mk0681 Glad to hear that :slight_smile: