3

With Postman it is possible to save a special field from the response body into a variable and use the value of this variable in a consecutive call.

For example: in my first call to the webservice the following is returned in the response body

[ {
  "id" : "11111111-1111-1111-1111-111111111111",
  "username" : "user-1@example.com",
}, {
  "id" : "22222222-2222-2222-2222-222222222222",
  "username" : "user-2@example.com"
} ]

I have added a test

postman.setGlobalVariable("user_0_id", JSON.parse(responseBody)[0].id);

Now I send a consecutive request to the webservice with the URL

http://example.com/users/{{user_0_id}}

Postman evaluates {{user_0_id}} to 11111111-1111-1111-1111-111111111111.

This works fine. But now I add to the test of my first call

postman.setGlobalVariable("users", JSON.parse(responseBody));

In my second request to the webservice I call the URL

http://example.com/users/{{users[0].id}}

But now {{users[0].id}} cannot be evaluated, it stays the same and is not replaced by 11111111-1111-1111-1111-111111111111.

What can I do? What is the correct syntax of the call?

Johannes Flügel
  • 3,112
  • 3
  • 17
  • 32
  • Does this answer your question? [Postman: Can i save JSON objects to environment variable so as to chain it for another request?](https://stackoverflow.com/questions/41479494/postman-can-i-save-json-objects-to-environment-variable-so-as-to-chain-it-for-a) – Henke Feb 02 '21 at 16:54

1 Answers1

6

To save an array in a global/environment variable, you'll have to JSON.stringify() it. Here's an excerpt from the Postman documentation about environments:

Environment and global variables will always be stored as strings. If you're storing objects/arrays, be sure to JSON.stringify() them before storing, and JSON.parse() them while retrieving.

If it is really necessary that you save the whole response, do something like this in your tests for the first call:

var jsonData = JSON.parse(responseBody);
// test jsonData here

postman.setGlobalVariable("users", JSON.stringify(jsonData));

To retrieve a user's id from your global variable and use it in the request URL, you'll have to parse the global variable in the pre-request script of the second call and add the value to a "temporary variable" to use it in the URL:

postman.setGlobalVariable("temp", JSON.parse(postman.getEnvironmentVariable("users"))[0].id);

Hence, the second call's URL would be:

http://example.com/users/{{temp}}

In the tests for the second call, make sure to clear your temp variable at the end:

postman.clearGlobalVariable("temp");

This should do the trick for you. As far as I know, there is currently no possibility to parse the global variable directly in the URL to access specific entries (like you tried to do with {{users[0].id}}).

Fabian Nack
  • 704
  • 7
  • 7
  • 1
    Seems like the syntax has changed and now to set the global variable you should use: `pm.global.set` instead of `postman.setGlobalVariable` – Ilya May 22 '18 at 08:16