Stop copying & pasting the response key value to your variable, and let's automate this action using the coming marvelous way with considering that you are returning a response similar to the below schema:
At first, I will hypothesize that you have defined a `token`
variable as a Global scope
. Postman has multiple tabs under the URL
input, especially the Tests
tab, go ahead and open it, then write the next JavaScript
code:
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 endpoint
that you need, and at last write the following code:
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: