STORING THE TOKEN AUTOMATICALLY
Jan 25, 2024 Copy Link
Stop Copying & Pasting the response key value to your variable and let's automate this action using the coming marvelous way with consideration that you are returning a response same the below schema:
{
"key": "success",
"msg": "You have logged in successfully",
"data": {
"name": "Mahmoud Ramadan",
"token": "1|7XJ3hr2HZmQD24D9fkKYrmPB6ivCo7b9imbUP7NA"
}
}
At first, I will hypothesize that you have defined a `token`
variable as a Global scope
. Postman has multi-tabs under the URL
input, especially the Tests
tab, go ahead and open it then write the next JavaScript
code:
var response = JSON.parse(responseBody);
pm.globals.set("token", response.data.token);
There are two ways to run these scripts, I have already mentioned one way which is the
`Tests`
tab in addition, you can use the`Pre-request Script`
tab to run scripts before dispatching the requests.
We can not run the former script in the
`Pre-request Script`
tab that's because, before dispatching the request Postman will search for the`data`
key object and will not find it, so it will fire an error.
Now, let's look at that variable after you have sent the request. Boom..the value has been populated 🚀
Hmm..I think that we often deal with Postman Collections
so, let's do so and create the `token`
variable in your C
ollection
then choose an end-point
that you need, and at last write the coming code:
var response = JSON.parse(responseBody);
pm.collectionVariables.set("token", response.data.token);
Then if you dispatch the request again you will find that the variable has been filled again!
To dive into the many ways of defining the variables in Postman, I recommend reading that Article.
To evade any errors, you can check whether the response contains a `data`
object or not because we may not receive a response for some reason, to avoid Postman from triggering an error about missing that key:
var response = JSON.parse(responseBody);
if (response.data !== undefined && response.data.token !== undefined) {
pm.collectionVariables.set("token", response.data.token);
}