✨ Testing
API Testing with Postman
Last updated: 2025-09-25 12:47:03
API Testing with Postman
Master API testing using Postman for comprehensive testing of REST APIs, including automated testing and collection management.
Postman Basics
Creating Requests
// GET request example
GET https://jsonplaceholder.typicode.com/posts
// POST request with JSON body
POST https://api.example.com/users
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}
// PUT request for updates
PUT https://api.example.com/users/123
Authorization: Bearer {{access_token}}
{
"name": "John Smith",
"email": "johnsmith@example.com"
}Environment Variables
// Environment setup
{
"base_url": "https://api.example.com",
"api_key": "your-api-key-here",
"user_id": "123",
"access_token": "jwt-token-here"
}
// Using variables in requests
GET {{base_url}}/users/{{user_id}}
Authorization: Bearer {{access_token}}
X-API-Key: {{api_key}}Pre-request Scripts
// Generate timestamp
pm.environment.set("timestamp", new Date().getTime());
// Generate random data
pm.environment.set("random_email", `user${Math.floor(Math.random() * 1000)}@test.com`);
// Set authentication token
const token = pm.environment.get("refresh_token");
if (token) {
pm.request.headers.add({
key: "Authorization",
value: `Bearer ${token}`
});
}
// Calculate signature for API
const timestamp = new Date().getTime();
const apiKey = pm.environment.get("api_key");
const secret = pm.environment.get("api_secret");
const signature = CryptoJS.HmacSHA256(timestamp + apiKey, secret).toString();
pm.environment.set("signature", signature);
pm.environment.set("timestamp", timestamp);Test Scripts
// Basic status code test
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// Response time test
pm.test("Response time is less than 500ms", function () {
pm.expect(pm.response.responseTime).to.be.below(500);
});
// JSON response validation
pm.test("Response is JSON", function () {
pm.response.to.be.json;
});
// Response body validation
pm.test("Response contains required fields", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('id');
pm.expect(jsonData).to.have.property('name');
pm.expect(jsonData.email).to.include('@');
});
// Array validation
pm.test("Response is an array with items", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.be.an('array');
pm.expect(jsonData).to.have.lengthOf.at.least(1);
});
// Save response data to environment
pm.test("Save user ID from response", function () {
const jsonData = pm.response.json();
if (jsonData && jsonData.id) {
pm.environment.set("user_id", jsonData.id);
}
});Advanced Testing Scenarios
// Test for specific error codes
pm.test("Unauthorized access returns 401", function () {
pm.response.to.have.status(401);
const jsonData = pm.response.json();
pm.expect(jsonData.error).to.equal("Unauthorized");
});
// Schema validation
const schema = {
"type": "object",
"required": ["id", "name", "email"],
"properties": {
"id": {
"type": "number"
},
"name": {
"type": "string",
"minLength": 1
},
"email": {
"type": "string",
"format": "email"
}
}
};
pm.test("Response matches schema", function () {
const jsonData = pm.response.json();
pm.expect(tv4.validate(jsonData, schema)).to.be.true;
});
// Pagination testing
pm.test("Pagination works correctly", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property('data');
pm.expect(jsonData).to.have.property('meta');
pm.expect(jsonData.meta).to.have.property('page');
pm.expect(jsonData.meta).to.have.property('total');
});Collection Runner & Newman
# Install Newman (CLI runner)
npm install -g newman
# Run collection from file
newman run collection.json -e environment.json
# Run with HTML report
newman run collection.json -e environment.json -r html --reporter-html-export report.html
# Run with multiple iterations
newman run collection.json -e environment.json -n 10
# Run with data file
newman run collection.json -e environment.json -d test-data.csv
# CI/CD integration example (GitHub Actions)
name: API Tests
on: [push, pull_request]
jobs:
api-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install Newman
run: npm install -g newman
- name: Run API Tests
run: newman run postman/collection.json -e postman/environment.json --reporters cli,junit --reporter-junit-export results.xmlMock Servers
// Create mock server responses
// GET /users
{
"users": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"status": "active"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane@example.com",
"status": "inactive"
}
],
"meta": {
"total": 2,
"page": 1,
"per_page": 10
}
}
// POST /users (201 Created)
{
"id": 3,
"name": "{{$randomFullName}}",
"email": "{{$randomEmail}}",
"status": "active",
"created_at": "{{$isoTimestamp}}"
}
// Error response (400 Bad Request)
{
"error": "Validation failed",
"details": {
"email": ["Email is already taken"],
"name": ["Name is required"]
}
}