Tired of updating your json payload (attribute) let Postman do it for you with a script and variable
Sometimes you need to generate new timestamps or id’s or … for every new request you send with POSTMAN. The solution is to use pre-request scripts. These scripts are Javascripts that will use macros to populate values in your body content (json in my case).
With the following JSON
1 2 3 4 5 |
{ "title": "this is a test", "timestamp": "{{TIMESTAMP}}", "id": "{{ID_COUNTER}}" } |
And the following pre-request script
1 2 3 4 5 6 7 8 9 10 11 12 |
var current_timestamp = new Date(); pm.environment.set("TIMESTAMP", current_timestamp.toISOString()); var counter = pm.environment.get("ID_COUNTER") if( counter == null ) { counter = 1; } else { counter = parseInt( counter ) + 1; } counter = String(counter).padStart(4,'0'); console.log("counter "+(counter)); pm.environment.set("ID_COUNTER",counter); |
then you can get the following result
1 2 3 4 5 |
{ "id": "0003", "timestamp": "2023-05-30T13:00:27.372Z", "title": "this is a test" } |
Inserting a json attribute from one query into another using a script and variable
In my case I was first querying to get a authentication token CSRF_NONCE that I should use in the forthcoming queries as a header.
Step 1) Query for a token
GET https://my.super-secret.server.com/api/security/csrf
Using Basic Authentication (Username/Password)
I would get back a json payload like this
1 2 3 4 5 6 7 8 9 10 11 |
{ "items": [ { "id": "csrf", "attributes": { "nonce_key": "CSRF_NONCE", "nonce": "g7/G7HDpdtG0tsI4yfWkiUC8Xbr90ZpW8e++gzGELqnF84dw4f6v3kHRAqXM14RQz9GL2RWRGeyOh/UKsI321EXfQ+CFhPhdsMqvuCKHE7bf0o5usNKO3AezJbX/z/Fb1PqhvlutH/7agKF8wvDwjiCKSw==" } } ] } |
Now let’s create a script that extracts that nonce token
NOTE ! You use “Post-response” script to the left
The script could be something like this
1 2 3 4 5 6 |
var jsonData = pm.response.json(); var nonce = jsonData.items[0].attributes.nonce; pm.globals.set("NONCE", nonce ); console.log("NONCE = "+nonce); |
Step 2) Query for the data
Add the header attribute CSRF_NONCE in my case, and set the value to {{NONCE}} which was the variable you set above in the script.
After the query in Step 1) has been executed you can verify that the global variable has received the right value by going to the following view
You can also see the value in the POSTMAN Console
Superb and well-thought-out content! If you need some information about Airport Transfer, then have a look at UY5