Postman API Testing Advanced: From Request Debugging to Automated Testing

Postman is an essential tool for API development and testing. Beyond basic request debugging, Postman offers powerful automated testing capabilities.

Writing Test Scripts

Postman supports executing JavaScript scripts before and after requests.

Pre-request Script

// Executed before the request is sent
const timestamp = new Date().getTime();
pm.variables.set("timestamp", timestamp);

// Generate signature
const apiKey = pm.environment.get("API_KEY");
const signature = CryptoJS.HmacSHA256(timestamp.toString(), apiKey).toString();
pm.request.headers.add({
    key: "X-Signature",
    value: signature
});

Tests Script

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

// Verify response body
pm.test("Response has data", function () {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property("data");
    pm.expect(jsonData.data).to.be.an("array");
});

// Save variable for subsequent requests
const token = pm.response.json().token;
pm.collectionVariables.set("auth_token", token);

Collections and Folders

API Collection
├── Auth
│   ├── Login
│   └── Refresh Token
├── Users
│   ├── GET /users
│   ├── POST /users
│   └── DELETE /users/:id
└── Products
    ├── GET /products
    └── POST /products

Environment Management

Environment Variable Example
Development base_url: http://localhost:3000
Staging base_url: https://staging-api.example.com
Production base_url: https://api.example.com

Newman CLI Integration

# Install Newman
npm install -g newman

# Run collection
newman run collection.json \
  -e environment.json \
  --reporters cli,htmlextra

# CI/CD Integration
newman run collection.json \
  --reporters junit \
  --reporter-junit-export results.xml

Monitors

Postman Monitors can run API tests on a schedule to monitor API health status.