The Postman API testing process can be automated using ChatGPT. The script is only for Postman collection. It creates a bearer token that expires every 15 minutes. The token is stored in a variable called 'bearerToken' and can be refreshed if necessary.The Postman API testing process can be automated using ChatGPT. The script is only for Postman collection. It creates a bearer token that expires every 15 minutes. The token is stored in a variable called 'bearerToken' and can be refreshed if necessary.

Simplify API Testing with One Simple Postman Script

2025/08/21 22:24
3분 읽기
이 콘텐츠에 대한 의견이나 우려 사항이 있으시면 crypto.news@mexc.com으로 연락주시기 바랍니다

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:

    Live action of the script

:::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.

시장 기회
체인스왑 로고
체인스왑 가격(TOKEN)
$0.002497
$0.002497$0.002497
+2.54%
USD
체인스왑 (TOKEN) 실시간 가격 차트
면책 조항: 본 사이트에 재게시된 글들은 공개 플랫폼에서 가져온 것으로 정보 제공 목적으로만 제공됩니다. 이는 반드시 MEXC의 견해를 반영하는 것은 아닙니다. 모든 권리는 원저자에게 있습니다. 제3자의 권리를 침해하는 콘텐츠가 있다고 판단될 경우, crypto.news@mexc.com으로 연락하여 삭제 요청을 해주시기 바랍니다. MEXC는 콘텐츠의 정확성, 완전성 또는 시의적절성에 대해 어떠한 보증도 하지 않으며, 제공된 정보에 기반하여 취해진 어떠한 조치에 대해서도 책임을 지지 않습니다. 본 콘텐츠는 금융, 법률 또는 기타 전문적인 조언을 구성하지 않으며, MEXC의 추천이나 보증으로 간주되어서는 안 됩니다.

$30,000 in PRL + 15,000 USDT

$30,000 in PRL + 15,000 USDT$30,000 in PRL + 15,000 USDT

Deposit & trade PRL to boost your rewards!