QA

Useful Scripts for Pre-request and Post-response in Postman

Pre-request and Post-response scripts are crucial scripting features in Postman for API testing. By utilizing these features efficiently, you can improve the accuracy of automated testing and streamline your workflows. This article provides an in-depth explanation of these scripts, from the basics to advanced applications, along with practical script examples and tips for effective usage

1. Useful Script Examples for Pre-request

Pre-request scripts are executed before sending a request. These scripts can automate pre-request preparations and enable efficient API testing. Let’s look at some examples.

1.1. Automatic Generation of JWT Tokens

Many APIs require authentication. If your API uses JWT tokens, this script can automatically generate a token for each request.

const header = {
    "alg": "HS256",
    "typ": "JWT"
};
const payload = {
    "sub": "user@example.com",
    "name": "John Doe",
    "admin": true
};
const secret = "your-256-bit-secret";
const token = jwt.sign(payload, secret, { algorithm: 'HS256', header: header });

pm.environment.set("jwt_token", token);

 

Key Points:

  • Security Management: The secret key used for token generation should be stored securely (e.g., in Postman environment variables or encrypted vaults).
  • Dynamic Payload: Modify the payload dynamically based on your test scenarios to simulate various user patterns.

 

1.2. Setting the Current Timestamp

If your API requires a timestamp, this script can generate and set it easily.

var timestamp = Math.floor(Date.now() / 1000);
pm.environment.set("current_timestamp", timestamp);

 

Use Cases:

  • Use in the exp field for authentication token expiration.
  • Time-sensitive API testing (e.g., retrieving data within a specific time frame).

 

1.3. Generating Random Data

Random data generation is useful for load testing or testing with unexpected inputs.

// ランダムな文字列
var randomString = Math.random().toString(36).substring(7);
pm.environment.set("random_string", randomString);

// ランダムなUUID
const uuid = require('uuid');
pm.environment.set("random_uuid", uuid.v4());

 

Note: Combining random data generation with other test scripts can help uncover unexpected errors or bugs.

 

2. Useful Script Examples for Post-response

Post-response scripts are executed after receiving a response. They help verify API behavior and efficiently utilize response data.

2.1. Verifying the Status Code

A basic script to check the status code.

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

 

Best Practice:
Prepare tests for error statuses (e.g., 400, 404, 500) in advance to validate API error handling.

 

2.2. Validating Response Data

You can check if specific fields or values in the response meet expectations.

pm.test("Response has user_id", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('user_id');
});

 

2.3. Using Response Data in Subsequent Requests

Extract data from the response and use it in subsequent requests.

var jsonData = pm.response.json();
pm.environment.set("user_id", jsonData.user_id);

 

Tip: Chaining data simplifies the creation of complex test scenarios.

 

2.4. Verifying Response Time

Test whether the response is returned within a specified time.

pm.test("Response time is less than 500ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(500);
});

 

3. Advanced Uses of Pre-request and Post-response

3.1. Building Test Suites

Link multiple requests to build a test suite as follows:

  • Pre-request: Generate tokens and dynamic variables for each request.
  • Post-response: Pass results from each request to subsequent ones.

 

3.2. Utilizing Custom Libraries

Postman allows importing Node.js libraries using require. For example, you can use encryption libraries to generate secure tokens.

const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('example').digest('hex');
pm.environment.set("hash_value", hash);

 

 

4. Key Points for Effective Use

Combining Pre-request and Post-response scripts allows for efficient preparation and validation during API testing.

Purpose Pre-request Post-response
Generate tokens or data before sending requests
Set environment or global variables
Generate random data
Validate response data
Save response data to variables
Perform API performance tests

 

5. Tips for Creating More Advanced Tests

  1. Testing for Error Patterns: Test not only normal cases but also abnormal cases (e.g., invalid tokens, incorrect input data) to ensure API robustness.
  2. Integrating with CI/CD Pipelines: Integrate Postman scripts with CI/CD tools (e.g., Jenkins, GitLab CI) to immediately verify API changes.
  3. Performance Monitoring: Add scripts to measure response time or conduct load testing to monitor API performance.

 

6. Conclusion

Pre-request and Post-response scripts in Postman are powerful tools for streamlining API testing. By leveraging these scripts, you can easily create complex test scenarios and generate dynamic data. Use this article as a reference to build a more advanced testing environment!