Wednesday, August 20, 2025

๐Ÿš€ Boosting API Testing with Pre-request and Post-response Scripts in Postman

As I’ve been working on API development and testing, I recently explored how to use Pre-request and Post-response scripts in Postman to automate and streamline my workflow. Here’s what I learned and how you can apply it too!


๐Ÿ”ง Pre-request Script: Dynamic Timestamping

I needed to send a request with a timestamp that was exactly 5 hours before the current time. Here’s the script I used:

let now = new Date();
let hour = 60 * 60 * 1000;
let multiplyer = 5;

let time_iso = new Date(now.getTime() - multiplyer * hour);
pm.environment.set("time_iso", time_iso.toISOString());

✅ This script calculates the time offset and stores it in an environment variable time_iso, which I then used in the request body like this:

{
  "timestamp": "{{time_iso}}"
}


๐Ÿ” Authorization Setup

To authenticate the request, I used a Bearer Token in the Authorization tab:

  • Type: Bearer Token
  • Token: {{auth_token}} (stored in environment variables)

Alternatively, you can add it manually in the Headers tab:

Key: Authorization
Value: Bearer {{auth_token}}

๐Ÿงช Post-response Script: Status Check and Token Extraction

After the request, I wanted to validate the response and extract a token for future use. Here’s the script I used:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});

let responseData = pm.response.json();

if (responseData.token) {
    pm.environment.set("auth_token", responseData.token);
    console.log("Token saved to environment:", responseData.token);
} else {
    console.warn("Token not found in response");
}

✅ This script checks if the response was successful and saves the token to an environment variable for reuse.


๐Ÿ’ก Final Thoughts

Using these scripts has made my API testing more dynamic and efficient. I can now automate timestamp generation, handle authentication seamlessly, and extract data from responses without manual effort.

If you're working with APIs in Postman, I highly recommend exploring these scripting features—they’re simple to implement and incredibly powerful!


No comments: