Postman tips - Autosave auth token on the session

rf_schubert profile image Raphael Schubert ・1 min read

As a dev, you have to test your API endpoints every time, and if it is a bit evolved, it has a login endpoint that you need to evoke to get the auth token to work.

Imagine you have this response from /api/login endpoint

    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3N1ZWQiOiIyMDE5LTAzLTA0VDE2OjQ2OjAzLjMyMDU1NC0wMzowMCIsImV4cGlyZXMiOiIyMDE5LTAzLTA0VDE2OjQ3OjAzLjMyMDYxOS0wMzowMCIsInNjb3BlcyI6ZmFsc2V9.cbPmdag39wvttxLHHe2BfOHUjM6vHDJ52WvoSxqLLF4g"

Normally you need to get the response, copy/paste on your session to be able to use on every endpoint on Postman.

But you can do something best, you can configure your Postman to save the token on your session when you just logged in!

Go on the Tests tab on your Postman:
Postman request tabs

Put this config:

var jsonData = JSON.parse(responseBody);
pm.environment.set("token", jsonData.token);

Tada!!! This will save the response of the request on the current environment with the var name as token, and now you can use on your routes just configuring it like this:

Postman request headers

Now you can just do your login anytime and Postman will automatically save the token on your environment and all endpoints will be able to use it with no efforts.



Editor guide
dannydainton profile image
Danny Dainton

Awesome! Thanks for sharing this tip with others :)

You could even go one further and reduce this to a single line:

pm.environment.set("token", pm.response.json().token); :)