AUTOMATICALLY STORING TOKENS

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 considering that you are returning a response similar to 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 multiple 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 Collection then choose an endpoint that you need, and at last write the following 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);
}

Share via

Mahmoud Ramadan

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.

Newly published

  • How to Enable Relationship Autoloading in Versions Before v12.8

    How to Enable Relationship Autoloading in Versions Before v12.8

    PREMIUM

  • Get your environment ready to welcome Laravel v12

    Get your environment ready to welcome Laravel v12

    PREMIUM

  • How to generate Arabic PDF using TCPDF

    How to generate Arabic PDF using TCPDF

    FREE