Pre-request Scripts in Postman
Khadija Tabassum
SQA Engineer | POSTMAN/SWAGGER(API) | WEB | ANDROID | IOS | JMETER(PERFORMANCE)| DATABASE | TECHNICAL DOCUMENTATION |ZAP(SECURITY) | FIREBASE(A/B)TESTING | ECOMMERCE/HEALTH/FLEET MANAGMENT SYSTEM |IOT
In Postman API testing, pre-scripts (also known as pre-request scripts) and post-scripts (test scripts) are used to add dynamic behavior to your requests. Here’s an explanation with real-life examples:
Pre-request Scripts
Pre-request scripts are snippets of code associated with a collection request that are executed before the request is sent. They can be used to:
Pre-request Scripts in Postman: Simplified Explanation with E-commerce Example
Pre-request scripts in Postman are scripts executed before the main API request is sent. They can be used to set up necessary conditions or data for the request.
Example Scenario: E-commerce App
Let's say you are testing an e-commerce app's API, and you need to create a new product. The API requires a unique product ID, which you will generate dynamically in the pre-request script.
Step-by-Step Example
1. Generating a Unique Product ID
Pre-request Script:
// Pre-request Script
var uuid = require('uuid');
var productId = uuid.v4(); // Generates a unique identifier
pm.environment.set('product_id', productId);
In this script, we use the uuid library to generate a unique product ID and store it in an environment variable called product_id.
2. Creating a New Product Request
API Request:
Headers: Content-Type: application/json
Body (raw JSON):
{ "id":
"{{product_id}}", "name": "New Product", "price": 29.99, "category": "Electronics" }
领英推荐
In this request, we use the {{product_id}} variable, which was set in the pre-request script, to ensure each product created has a unique ID.
3. Validating the Response
Test Script:
Test scripts are executed after a request has been sent and a response has been received. They can be used to:
Suppose you are verifying that a user registration API returns a 201 status code and includes a user ID in the response.
Sending the Request:
Body: { "username": "john_doe", "password": "securepassword123" }
Test Script to Validate Response:
// Test Script
pm.test("Status code is 201", function () {
pm.response.to.have.status(201); });
pm.test("Response has product ID", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('id'); });
In this script, we validate that the response status code is 201 (Created) and that the response body contains the product ID.
Summary
Pre-request Script: Generates a unique product ID before the API request is sent.
API Request: Uses the generated product ID to create a new product.
Test Script: Validates the response to ensure the product was created successfully.
This example demonstrates how pre-request scripts can be used to dynamically generate data needed for API requests in a simplified and practical e-commerce scenario.