0% found this document useful (0 votes)
21 views14 pages

API Document L

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views14 pages

API Document L

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

How to Use Postman for API Test Automation

A Comprehensive Guide for Automation Engineers

Table of Contents

1.​ Introduction to Postman


2.​ Getting Started
3.​ Understanding the Postman Interface
4.​ Creating and Managing Collections
5.​ Writing API Tests
6.​ Automation Fundamentals
7.​ Advanced Testing Features
8.​ CI/CD Integration
9.​ Best Practices and Tips
10.​ Troubleshooting Guide
11.​ Advanced Scripting Techniques
12.​ Performance Testing
13.​ Security Testing
14.​ Team Collaboration
15.​ Reporting and Analytics
16.​ Real-World Use Cases
17.​ Advanced Automation Scenarios
18.​ Visual Documentation

1. Introduction to Postman

Postman is a powerful API platform that enables automation engineers to streamline


their API testing workflow. This guide will walk you through everything you need to
know to become proficient in using Postman for automation testing.

Key Benefits

●​ Simplified API testing process


●​ Robust automation capabilities
●​ Excellent team collaboration features
●​ Comprehensive test reporting
●​ Easy CI/CD integration
2. Getting Started

Installation and Setup

1.​ Download Postman from www.postman.com


2.​ Create a Postman account
3.​ Install Postman's native app for your operating system
4.​ Configure your workspace settings
5.​

Initial Configuration

// Example of environment variable setup​


{​
"base_url": "https://api.example.com",​
"auth_token": "{{your_auth_token}}",​
"timeout": 5000​
}

3. Understanding the Postman Interface

Key Components

●​ Collections pane
●​ Request builder
●​ Response viewer
●​ Environment selector
●​ Console
●​ Test scripts area

4. Creating and Managing Collections

Collection Structure

my-api-tests/​
├── auth/​
│ ├── login​
│ └── logout​
├── users/​
│ ├── create​
│ ├── read​
│ ├── update​
│ └── delete​
└── products/​
├── list​
└── search
Best Practices for Organization

●​ Use descriptive names


●​ Group related requests
●​ Maintain consistent structure
●​ Include documentation
●​ Version control integration

5. Writing API Tests


Basic Test Structure

pm.test("Status code is 200", function () {​


pm.response.to.have.status(200);​
});​

pm.test("Response time is acceptable", function () {​
pm.expect(pm.response.responseTime).to.be.below(200);​
});​

pm.test("Content-Type header is present", function () {​
pm.response.to.have.header("Content-Type");​
});

Advanced Test Scenarios

// Schema validation​
const schema = {​
"type": "object",​
"properties": {​
"id": { "type": "integer" },​
"name": { "type": "string" },​
"email": { "type": "string" }​
},​
"required": ["id", "name", "email"]​
};​

pm.test("Schema validation", function () {​
pm.response.to.have.jsonSchema(schema);​
});

// Data validation​
pm.test("User data is correct", function () {​
const responseData = pm.response.json();​
pm.expect(responseData.name).to.eql("John Doe");​
pm.expect(responseData.email).to.match(/@.*\./);​
});
6. Automation Fundamentals

Pre-request Scripts
// Setting dynamic variables
pm.environment.set("timestamp", Date.now());

// Generate random data


const uuid = require('uuid');
pm.environment.set("user_id", uuid.v4());

Test Data Management

// Loading test data from file


let testData = JSON.parse(pm.environment.get("testData"));

// Iterating through test cases


testData.forEach(function(data) {
pm.test(`Test case: ${data.description}`, function () {
pm.expect(pm.response.json()).to.include(data.expectedResult);
});
});

7. Advanced Testing Features

Newman CLI

# Running collections from command line


newman run mycollection.json -e environment.json

# Generating HTML reports


newman run mycollection.json -r htmlextra

Monitors and Scheduling


●​ Setting up monitoring
●​ Scheduling periodic runs
●​ Alert configuration
●​ Performance tracking

8. CI/CD Integration
Jenkins Integration

pipeline {
agent any
stages {
stage('API Tests') {
steps {
sh 'newman run collection.json -e env.json'
}
}
}
}
GitHub Actions
name: API Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Newman
run: npm install -g newman
- name: Run API Tests
run: newman run collection.json -e env.json

9. Best Practices and Tips

Code Organization

●​ Use descriptive test names


●​ Implement proper error handling
●​ Maintain test independence
●​ Follow DRY principles
●​ Document assertions

Performance Optimization

// Parallel execution setup


{
"collection": {
"runner": {
"iterations": 100,
"parallel": 10
}
}
}

10. Troubleshooting Guide

Common Issues and Solutions

1.​ Authentication failures


○​ Check token expiration
○​ Verify credentials
○​ Inspect request headers
2.​ Performance issues
○​ Monitor response times
○​ Check for memory leaks
○​ Optimize test scripts
3.​ Data consistency
○​ Validate test data
○​ Check environment variables
○​ Review dependencies
Debug Techniques

// Console logging for debugging


console.log("Request payload:", pm.request.body);
console.log("Response:", pm.response.json());
console.log("Environment variables:", pm.environment.toObject());

11. Advanced Scripting Techniques

Working with External Libraries

// Using moment.js for date manipulation


const moment = require('moment');
const futureDate = moment().add(7, 'days').format('YYYY-MM-DD');
pm.environment.set("future_date", futureDate);

// Using crypto-js for encryption


const CryptoJS = require('crypto-js');
const encrypted = CryptoJS.AES.encrypt(
pm.environment.get("sensitive_data"),
pm.environment.get("encryption_key")
).toString();
pm.environment.set("encrypted_data", encrypted);

Custom Functions and Utilities

// Reusable test functions


const utils = {
validateEmail: function(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
},

generateRandomString: function(length) {
return Array(length)
.fill('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
.map(x => x[Math.floor(Math.random() * x.length)])
.join('');
},

validateStatusCode: function(expectedStatus) {
pm.test(`Status code is ${expectedStatus}`, () => {
pm.response.to.have.status(expectedStatus);
});
}
};

// Using utility functions


utils.validateStatusCode(200);
const randomString = utils.generateRandomString(10);

12. Performance Testing

Load Testing Configuration

// Newman CLI with load testing parameters


{
"config": {
"timeoutRequest": 5000,
"delayRequest": 100,
"poolSize": 50,
"iterations": 1000,
"bail": false,
"suppressExitCode": false
}
}

Response Time Analysis

// Performance metrics collection


pm.test("Performance thresholds", () => {
// Basic response time check
pm.expect(pm.response.responseTime).to.be.below(200);

// Store metrics for trending


const metrics = {
timestamp: new Date().toISOString(),
responseTime: pm.response.responseTime,
endpoint: pm.request.url.toString(),
method: pm.request.method,
status: pm.response.status
};

// Get existing metrics array or initialize new one


let performanceMetrics = JSON.parse(
pm.environment.get("performanceMetrics") || "[]"
);

// Add new metrics and maintain last 100 entries


performanceMetrics.push(metrics);
if (performanceMetrics.length > 100) {
performanceMetrics.shift();
}

pm.environment.set(
"performanceMetrics",
JSON.stringify(performanceMetrics)
);
});

13. Security Testing

Security Headers Validation

pm.test("Security headers are present", () => {


const requiredHeaders = [
"Strict-Transport-Security",
"X-Content-Type-Options",
"X-Frame-Options",
"X-XSS-Protection",
"Content-Security-Policy"
];

requiredHeaders.forEach(header => {
pm.response.to.have.header(header);
});
});
Authentication Testing

// OAuth 2.0 token validation


pm.test("OAuth token is valid", () => {
const token = pm.response.json().access_token;

// Verify token structure


pm.expect(token).to.match(/^[\w-]*\.[\w-]*\.[\w-]*$/);

// Decode JWT token


const [header, payload, signature] = token.split('.');
const decodedPayload = JSON.parse(atob(payload));

// Validate token claims


pm.expect(decodedPayload).to.have.property('exp');
pm.expect(decodedPayload.exp * 1000).to.be.above(Date.now());
pm.expect(decodedPayload.aud).to.equal(pm.environment.get("client_id"));
});

14. Team Collaboration

Workspace Management

●​ Setting up team workspaces


●​ Access control and permissions
●​ Version control integration
●​ Team documentation
●​ Shared environments

Code Review Process

// Code review checklist in collection description


{
"info": {
"name": "API Tests",
"description": "# Code Review Checklist\n\n" +
"- [ ] Tests follow naming convention\n" +
"- [ ] All tests have assertions\n" +
"- [ ] Error scenarios covered\n" +
"- [ ] Documentation updated\n" +
"- [ ] Environment variables used\n" +
"- [ ] No hardcoded credentials"
}
}

15. Reporting and Analytics


Custom Report Generation

// Generate custom HTML report


const htmlReport = {
generateSummary: function(results) {
return `
<html>
<head>
<title>Test Results Summary</title>
</head>
<body>
<h1>Test Execution Summary</h1>
<div class="summary">
<p>Total Tests: ${results.total}</p>
<p>Passed: ${results.passed}</p>
<p>Failed: ${results.failed}</p>
<p>Average Response Time: ${results.avgResponseTime}ms</p>
</div>
</body>
</html>
`;
}
};

Metrics Collection

// Collecting test metrics


pm.test("Collect metrics", () => {
const metrics = {
timestamp: new Date().toISOString(),
endpoint: pm.request.url.toString(),
method: pm.request.method,
responseTime: pm.response.responseTime,
status: pm.response.status,
success: pm.response.to.have.status(200),
size: pm.response.size().body
};

// Store metrics for reporting


let testMetrics = JSON.parse(
pm.environment.get("testMetrics") || "[]"
);
testMetrics.push(metrics);
pm.environment.set("testMetrics", JSON.stringify(testMetrics));
});

16. Real-World Use Cases

E-commerce API Testing

// Product catalog testing


pm.test("Product catalog API", () => {
const response = pm.response.json();

// Verify product structure


pm.expect(response.products).to.be.an('array');
response.products.forEach(product => {
pm.expect(product).to.include.all.keys(
'id', 'name', 'price', 'inventory', 'category'
);
pm.expect(product.price).to.be.above(0);
pm.expect(product.inventory).to.be.at.least(0);
});

// Test pagination
pm.expect(response.pagination).to.deep.include({
currentPage: Number(pm.request.url.query.get('page')),
itemsPerPage: 20,
totalItems: pm.expect.any(Number)
});
});

// Shopping cart operations


const cartTests = {
addItem: () => {
const item = {
productId: "123",
quantity: 2,
customizations: {
size: "L",
color: "blue"
}
};

pm.sendRequest({
url: pm.environment.get("base_url") + "/cart",
method: "POST",
header: {
"Content-Type": "application/json",
"Authorization": pm.environment.get("token")
},
body: {
mode: "raw",
raw: JSON.stringify(item)
}
}, (err, response) => {
pm.test("Item added to cart", () => {
pm.expect(response.code).to.equal(200);
const cartItem = response.json().items.find(
i => i.productId === item.productId
);
pm.expect(cartItem).to.deep.include(item);
});
});
}
};

Banking API Scenarios

// Transaction processing
const bankingTests = {
validateTransaction: () => {
const transaction = pm.response.json();

pm.test("Transaction validation", () => {


// Basic transaction checks
pm.expect(transaction).to.include.all.keys(
'id', 'amount', 'type', 'status', 'timestamp'
);

// Amount validation
pm.expect(transaction.amount).to.be.above(0);
pm.expect(transaction.amount).to.be.a('number');

// Balance check
const newBalance = transaction.resultingBalance;
const oldBalance = pm.environment.get("previousBalance");
const expectedBalance = transaction.type === "CREDIT"
? oldBalance + transaction.amount
: oldBalance - transaction.amount;

pm.expect(newBalance).to.equal(expectedBalance);

// Store new balance


pm.environment.set("previousBalance", newBalance);
});

// Compliance checks
pm.test("Transaction compliance", () => {
if (transaction.amount > 10000) {
pm.expect(transaction.complianceChecks).to.include({
largeTransactionReported: true,
customerVerified: true
});
}
});
}
};

17. Advanced Automation Scenarios

Data-Driven Testing

// Example test data file (testData.json)


{
"userScenarios": [
{
"description": "Valid user registration",
"input": {
"email": "[email protected]",
"password": "ValidPass123!",
"age": 25
},
"expectedStatus": 201,
"expectedResponse": {
"status": "success",
"verified": false
}
},
{
"description": "Invalid email format",
"input": {
"email": "invalid-email",
"password": "ValidPass123!",
"age": 25
},
"expectedStatus": 400,
"expectedResponse": {
"status": "error",
"code": "INVALID_EMAIL"
}
}
]
}

// Data-driven test implementation


const testData = JSON.parse(pm.environment.get("testData"));

testData.userScenarios.forEach(scenario => {
pm.test(scenario.description, () => {
// Send request with scenario data
pm.sendRequest({
url: pm.environment.get("base_url") + "/users",
method: "POST",
header: { "Content-Type": "application/json" },
body: {
mode: "raw",
raw: JSON.stringify(scenario.input)
}
}, (err, response) => {
pm.expect(response.code).to.equal(scenario.expectedStatus);
pm.expect(response.json()).to.deep.include(
scenario.expectedResponse
);
});
});

});

Workflow Automation

// Complex workflow testing


const workflowTests = {
orderProcessing: async () => {
// Step 1: Create order
const orderResponse = await pm.sendRequest({
url: "/orders",
method: "POST",
body: { items: [{id: "123", quantity: 1}] }
});
const orderId = orderResponse.json().id;

// Step 2: Process payment


const paymentResponse = await pm.sendRequest({
url: "/payments",
method: "POST",
body: {
orderId: orderId,
amount: orderResponse.json().total
}
});
// Step 3: Verify order status
const statusResponse = await pm.sendRequest({
url: `/orders/${orderId}`,
method: "GET"
});

pm.test("Complete order workflow", () => {


pm.expect(statusResponse.json().status).to.equal("PAID");
pm.expect(statusResponse.json().payment).to.deep.include({
status: "SUCCESS",
amount: orderResponse.json().total
});
});
}
};

18. Visual Documentation

sequenceDiagram

participant C as Client
participant P as Postman
participant A as API
participant D as Database

C->>P: Initialize Test Suite


P->>P: Load Environment
P->>A: Authentication Request
A->>D: Validate Credentials
D->>A: User Data
A->>P: Auth Token
P->>P: Store Token
loop Test Execution
P->>A: API Request
A->>D: Process Request
D->>A: Response Data
A->>P: API Response
P->>P: Run Tests
P->>P: Update Environment
end
P->>C: Test Results

Conclusion
This guide covers the essential aspects of using Postman for API automation testing. By
following these practices and guidelines, you'll be able to create robust, maintainable, and
efficient API tests.

Follow https://www.linkedin.com/in/guneetsinghbali/

You might also like