Postman: A hands-on tutorial: Day 4 — A Deep Dive into a Postman Request: Part II

Dipan Saha
4 min readJan 15, 2024

--

Welcome back to Day 4 of our hands-on Postman tutorial series! This is the second part of the A Deep Dive into a Postman Request chapter. Today, we shall learn about Pre-Request scripts and Tests in a Postman Request.

Pre-request Scripts

A Pre-request Script in Postman is a piece of JavaScript code that runs before the actual API request is sent. This script provides an opportunity to manipulate the request, set variables dynamically, and perform actions based on certain conditions.

Whether you need to generate timestamps, calculate cryptographic signatures, or include dynamic data, Pre-request Scripts empower you to tailor your requests with precision.

Here are some common Use Cases for Pre-request Scripts -

1. Dynamic Variable Assignment:

  • Use Pre-request Scripts to set variables dynamically based on certain conditions or calculations.
// Example: Set a timestamp as a dynamic variable
pm.variables.set("timestamp", new Date().toISOString());

2. Conditional Logic:

  • Execute different actions or set parameters based on conditions.
// Example: Set an API key based on the environment
if (pm.environment.get("environment") === "production") {
pm.variables.set("api_key", "production_api_key");
} else {
pm.variables.set("api_key", "test_api_key");
}

3. Data Encryption:

  • Perform cryptographic operations before sending sensitive information.
// Example: Calculate HMAC-SHA256 signature
const secretKey = "your_secret_key";
const message = pm.request.url.toString();
const signature = CryptoJS.HmacSHA256(message, secretKey).toString(CryptoJS.enc.Hex);
pm.request.headers.add({key: "Signature", value: signature});

4. Dynamic Data Generation:

  • Generate data on-the-fly for specific parameters in the request.
// Example: Generate a random user ID
const randomUserId = Math.floor(Math.random() * 1000);
pm.request.body.raw = JSON.stringify({ "userId": randomUserId });

5. Environment Variable Manipulation:

  • Update environment variables based on the execution context.
// Example: Increment a counter in the environment
const counter = pm.environment.get("counter") || 0;
pm.environment.set("counter", counter + 1);

Tests

Postman Tests are scripts written in JavaScript that run after an API request is sent. These scripts enable developers to define validation criteria for the response received from the server. Postman supports scripting for automated testing.

Photo by Annie Spratt on Unsplash

Before we explore the practical aspects of writing tests in Postman, let’s break down the key components:

  1. Test Script Tab: Found within the Postman request, the “Tests” tab is where you write JavaScript code to define your tests.
  2. Chai Assertion Library: Postman leverages the Chai assertion library, providing a rich set of functions to express and validate expectations.
  3. Response Object: The response received from the server is available within the test script as the pm.response object, allowing you to inspect headers, body, status codes, and more.

Let’s write a simple test for a GET request:

  • Open a Request: Create or open a GET request in Postman.
  • Navigate to the Tests Tab: Click on the “Tests” tab next to the request builder.
  • Write a Test Script: Write a simple test script to check if the response status code is 200.
// Example Test Script 
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
  • Send the Request: Click on “Send” to execute the request and run the associated test script.

Here are some common Use Cases for Postman Tests:

1. Status Code Validation:

  • Ensure that the server returns the expected status code.
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});

2. Response Body Validation:

  • Validate specific content within the response body.
pm.test("Response body contains 'success'", function () {
pm.expect(pm.response.text()).to.include("success");
});

3. Header Validation:

  • Check if specific headers are present in the response.
pm.test("Content-Type header is present", function () {
pm.response.to.have.header("Content-Type");
});

4. Schema Validation:

  • Validate the response against a predefined schema.
const schema = {
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number" }
},
"required": ["name", "age"]
};
pm.test("Response follows the schema", function () {
pm.response.to.have.jsonSchema(schema);
});

Best Practices for Writing Postman Tests

  1. Clear and Concise: Keep your test scripts clear, concise, and focused on specific validation points.
  2. Error Handling: Include error-handling mechanisms in your scripts to gracefully handle unexpected scenarios.
  3. Parameterization: Leverage variables and dynamic data in your test scripts for flexibility.
  4. Documentation: Comment your code to provide clarity and documentation for other team members.

Here are some sample test scripts from Postman documentation site.

Conclusion

Congratulations! You’ve now learnt about how Pre-Request scripts and Tests are written in a Postman Request. Stay tuned for Day 5 where we will take a deep dive into the Postman Console.

Happy coding!

--

--

Dipan Saha

Cloud Architect (Certified GCP Professional Architect & Snowflake Core Pro)