By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
Reading: Simplify API Testing with One Simple Postman Script | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
World of Software > Computing > Simplify API Testing with One Simple Postman Script | HackerNoon
Computing

Simplify API Testing with One Simple Postman Script | HackerNoon

News Room
Last updated: 2025/08/21 at 10:57 PM
News Room Published 21 August 2025
Share
SHARE

For the past two months, I have been exploring API and software testing, and I can tell you it hasn’t been easy for me. I always thought, “Isn’t it just testing?” but I was wrong. Testing is about ensuring the application works as expected and identifying any vulnerabilities or issues within it.

Recently, I have been overwhelmed by copying IDs from one endpoint to another because the testing had to be done manually. One of the challenges is copying the bearer token and saving it.

Not-so-fun fact: This bearer token expires every 15 minutes.

I won’t lie; it’s exhausting and frustrating. Then today, something changed when a developer told me, “You should find a way for the bearer token to be generated automatically so you don’t have to go through the stress of copying the token every time.”

At first, it seemed impossible, but then I sat down, and after two hours with ChatGPT, I was able to create a script that automates this process for me.

The Automation Script and Breakdown

:::info
Note: This script is only for the Postman collection

:::

  1. In your environment, create the following variable and leave it empty:

    I. bearerToken

    ii. token_expiry

    iii. refreshToken if any necessary

  2. In your collection, add the following script to the Pre-req:

   // Base URL and path variables (replace with your own API details)
   let baseUrl = pm.variables.get("baseUrl"); 
   let parameter1 = pm.variables.get("parameter1");
   let parameter2 = pm.variables.get("parameter2");

   // Current timestamp
   let now = Math.floor(Date.now() / 1000);

   // --- Function: Login with username + password ---
   function loginWithCredentials() {
       let loginUrl = `${baseUrl}/${parameter1}/${parameter2}/Auth/token`;

       pm.sendRequest({
           url: loginUrl,
           method: "POST",
           header: { "Content-Type": "application/json" },
           body: {
               mode: "raw",
               raw: JSON.stringify({
                   // if the endpoint uses a body parameter pass it like this:
                   username: pm.variables.get("username"),   // from Postman environment
                   password: pm.variables.get("password")    // from Postman environment
               })
           }
       }, function (err, res) {
           if (!err && res.code === 200) {
               let data = res.json();

               // Store tokens + expiry time in Postman environment
               pm.environment.set("bearerToken", data.token);
               pm.environment.set("refreshToken", data.refreshToken);
               pm.environment.set("token_expiry", now + 900); // adjust according to your API

               console.log("Logged in successfully!");
           } else {
               console.error("Login failed:", err || res.text());
           }
       });
   }

   // --- Function: Refresh token ---
   function refreshAccessToken(refreshToken) {
       let refreshUrl = `${baseUrl}/${parameter1}/${parameter1}/Auth/refresh-token`;

       pm.sendRequest({
           url: refreshUrl,
           method: "POST",
           header: { "Content-Type": "application/json" },
           body: {
               mode: "raw",
               raw: JSON.stringify({
                   //if the refresh-token endpoint uses the previous token and refreshToken
                   token: token,
                   refreshToken: refreshToken
               })
           }
       }, function (err, res) {
           if (!err && res.code === 200) {
               let data = res.json();

               pm.environment.set("bearerToken", data.token);
               pm.environment.set("refreshToken", data.refreshToken || refreshToken);
               pm.environment.set("token_expiry", now + 900);

               console.log("Token refreshed successfully!");
           } else {
               console.log("Refresh failed. Falling back to login...");
               loginWithCredentials();
           }
       });
   }

   // --- Token handling logic ---
   let bearerToken = pm.environment.get("bearerToken");
   let refreshToken = pm.environment.get("refreshToken");
   let tokenExpiry = pm.environment.get("token_expiry");

   if (!bearerToken || now >= tokenExpiry) {
       console.log("Token expired or missing...");
       if (refreshToken) {
           refreshAccessToken(bearerToken, refreshToken);
       } else {
           loginWithCredentials();
       }
   } else {
       console.log("Token still valid.");
   }

  1. With this simple, yet powerful script, I don’t have to generate tokens by myself when testing.

    Here is a live action look:

:::info
Note: modify this script based on your endpoints. This means your Auth endpoint may not need a path parameter to generate a bearer token or vice-versa.

:::

I hope you find this useful. Like, share, and follow for more.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article The Best Wireless Gaming Mice for 2025
Next Article Musk’s X reaches tentative settlement with former Twitter workers in $500 million lawsuit
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

Spigen’s Pixel 10 range: all the protection you need for the phone you crave | Stuff
Gadget
China’s self-developed passenger aircraft C919 secures 1,200 orders · TechNode
Computing
Leaker Claims iPhone 17 Cases May Switch To Synthetic TechWoven Material – BGR
News
Fintech apps in Nigeria with competitive interest rates on savings
Computing

You Might also Like

Computing

China’s self-developed passenger aircraft C919 secures 1,200 orders · TechNode

1 Min Read
Computing

Fintech apps in Nigeria with competitive interest rates on savings

8 Min Read
Computing

Game Science art director’s dream inspires Black Myth: Zhong Kui · TechNode

4 Min Read
Computing

Luckin Coffee creates a no-coffee-added drink with Moutai in second partnership · TechNode

1 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright © All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?