Reputation: 62773
My app API requires authentication via an authentication token. In short, we send a request to a /authentication
endpoint and it responds with a JSON object containing a token, like:
{"token": "xxxxxxxxxxxxxxxxxxxxxx"}
Every other API endpoint in our application requires an authentication
header containing this token. Now, in Postman it's possible to do the authentication request, copy the token, open the next endpoint and paste the authentication
header in manually. But this becomes tedious and time-consuming when testing lots of endpoints.
Is there a way to have Postman save and automatically add the authentication
token from one request in any follow-up requests?
Even better, could Postman automatically send the /authentication
request prior to any of the other requests?
Upvotes: 3
Views: 3879
Reputation: 2943
Postman allows you a wide variety of options when crafting API requests.
In your case, You can create a global variable for your token when you receive it by:
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable('token', jsonData.token);
This would go in your Tests
tab, in order to execute this script after your request has been completed.
Now, a global variable token
is set and can be accessed using {{token}}
syntax in the following API requests you make.
I'll demonstrate it to you regarding the same, with a similar example:
1. Save the data of latitude and longitude into the global variables
lat
and long
.
2. Reuse the data by referring to the name of the variable, i.e.
lat
and long
by enclosing them within curly braces like {{lat}}
and {{long}}
.
- You can also manage these global variables, by clicking on the gear icon in the top right corner, and selecting manage environments then opening the Globals tab.
- Tip: You can also, save the request to obtain the token into your collections, so that each time, you don't have to craft the URL to obtain the token.
Upvotes: 8