Automatically setting variable based on api response?

Is there a way to automatically have a Variable updated based on an api’s response?

For example, if I hit a login endpoint, and receive “token” could I have {{token}} automatically updated in my local values?

2 Likes

Hi @Gravnos,

Yes, you can do this in a script. Under the Tests tab for the login request, you can pull the token from the response and store it in a variable. Depending on your use case, this might make sense as an environment variable.

Example of how this might be done in the Tests tab:

const response = pm.response.json();
pm.environment.set('token', response.token);

Then, making sure the environment is set, you can use the variable with the following syntax, wherever variables are supported: {{token}}.

More info here: https://learning.postman.com/docs/sending-requests/variables/

Hope this helps.

Best,

Kevin

3 Likes

Fantastic, thank you!

Does anyone have an update on how this might be done now?
I’ve tried parsing the JSON but I can’t seem to get the needed value.

@Victor1001

It’s probably best to post a new question, and include details\screenshots showing an example of your request\response and environment variables. (redacting as appropriate).

It might be that your token attribute isn’t at the top level of the JSON response, or the response might not even be JSON.