paint-brush
Streamlining API Testing with Postman’s Pre-Request Scriptsby@Kolapo
147 reads

Streamlining API Testing with Postman’s Pre-Request Scripts

by Kolapo ImamOctober 21st, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Postman pre-request scripts streamline testing of APIs. The scripts automatically generate a random 12-character transaction reference. This random reference is shared with other endpoints, making it easy for the APIs to access the same reference seamlessly. The value generated gets reused across any endpoint that needs it, keeping my testing smooth and consistent.
featured image - Streamlining API Testing with Postman’s Pre-Request Scripts
Kolapo Imam HackerNoon profile picture

As a Product Evangelist, I regularly test and demo various APIs to better understand their capabilities. For a very long time, Postman has been my go-to tool. It’s straightforward, reliable, and does the job well. But recently, I discovered a game-changing feature that took my exploration to a whole new level and that’s the Postman’s pre-request scripts.


Before now, I was running basic tests and manually inputting certain values even though I used variables for handling some auth, which worked fine but felt a little tedious over time. Yesterday, while playing around with Postman, I found a way to streamline my testing process using pre-request scripts, and the results were incredible.


I started with a simple need by generating a unique transaction reference for an endpoint. Rather than manually entering a reference each time, I used Postman’s UUID function to automatically create a random 12-character transaction reference.


function generateTransactionRef() {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < 12; i++) {
        const randomIndex = Math.floor(Math.random() * characters.length);
        result += characters[randomIndex];
    }
    return result;
}

var uniqueTransactionRef = generateTransactionRef();
pm.environment.set("transactionRef", uniqueTransactionRef);

console.log("Generated transactionRef:", uniqueTransactionRef);


This random reference was then shared with other endpoints, making it easy for the APIs to access the same reference seamlessly.


For example, one API requires a transactionref as part of the body to simulate transfer. With the script in place, I could automatically use the generated reference across multiple requests. This eliminated manual entry and potential errors. The value generated gets reused across any endpoint that needs it, keeping my testing smooth and consistent.


Another API I work with requires a token to be refreshed every 30 minutes. This was something I used to manage manually, which felt like a waste of time having to copy-paste every time the token expires. But using pre-request scripts, I automated the entire process. Now, Postman grabs the newly generated token from the first request and automatically inserts it as the bearer token for subsequent requests in the same environment.


var requestOptions = {
    url: 'URL to generate the token',
    method: 'POST',
    header: {
        'Content-Type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            "username": "user's email",
            "password": "user's password"
        })
    }
};

pm.sendRequest(requestOptions, function (err, res) {
    if (err) {
        console.error('Error fetching token:', err);
        return;
    }

    var jsonResponse = res.json();

    if (jsonResponse.statusCode === 90000 && jsonResponse.data && jsonResponse.data.token) {
        var token = jsonResponse.data.token;
        pm.environment.set('bearerToken', token);
        console.log('Token fetched and saved:', token);
    } else {
        console.error('Error: Token not found in the response. Response:', jsonResponse);
    }
});

pm.request.headers.add({
    key: 'Authorization',
    value: 'Bearer ' + pm.environment.get('bearerToken')
});


For all the other endpoints, the script picks up this token and adds it as the authorization header. This small tweak made my workflow far more efficient, as I no longer have to pause or copy-paste for manual token updates.


This new approach has 10x’d the way I test, demo, and document APIs. The flexibility and power of Postman’s scripting features have opened up new possibilities for how I approach my work. I’m excited to keep exploring more features to make my API testing even more seamless. Next on my list is setting up API monitoring. I’ve done it in the past but can’t quite remember all the steps. Once I get that up and running again, it’ll be another big win for making sure everything stays up and running smoothly.


Postman is more than just a tool for running API requests seeing that with a little scripting, it’s become a critical part of my workflow, allowing me to focus more on other important projects and less on repetitive tasks. If you haven’t started using pre-request scripts yet, I highly recommend giving them a try and they might just transform how you work. Let me know what you think about this short article and if I should be sharing more in this direction.