Postman: set Environment Variable

15.3k Views Asked by At

I have a POST call in Postman that returns this JSON object:

{
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiO3Jsb3Blei5hbnRvbmlvODVAZ21haWwuY29tIiwiZXhwIjoxNTkzNjc0MzUxLCJpYXQiOjE1MzMxOTQzNTF9.oTPVkcgF1QcoOsg6KDGOaaTyCQYrWS51QDdRn__MDigivcsuaqUgBhDaTYwQnxOtOCjxDRXO_cqK8i5xBq02bQ"
}

In my environment I set a variable named token

I want to set the value. I've tried with

var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", data.message.token);

and

var data = pm.response.json();
pm.environment.set("token", data.message.token);

but both with errors: SyntaxError | Invalid or unexpected token

4

There are 4 best solutions below

0
Danny Dainton On BEST ANSWER

If that's the only thing you get back in the response body, why are you adding 'message'?

Use data.token or just use pm.response.json().token and remove the variable declaration.

1
Atchutha rama reddy Karri On
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("TOKEN",jsonData.token);
0
Tahera Firdose On

In order to set the environment variable key use below

var response=pm.response.json();
pm.environment.set("tokenkey", response.token);
0
Paulo Merson On

The environment variables were not working for me after a Postman update. In my case the problem was that my environment was not set on the top right (it was using the default, "No Environment"). ‍♂️