🔥 0
0

Collections & Automation

Collections are the heart of API testing automation. They let you organize, run, and share your tests.

Collection Structure

A well-organized e-commerce collection:

📁 Shop API
  📁 Auth
     POST Login
     POST Register
     POST Logout
  📁 Products
     GET List Products
     GET Get Product by ID
     GET Search Products
     POST Create Product
     PUT Update Product
     DELETE Delete Product
  📁 Cart
     GET View Cart
     POST Add to Cart
     PUT Update Quantity
     DELETE Remove Item
     DELETE Clear Cart
  📁 Orders
     POST Create Order
     GET Get Order
     GET List Orders
     PUT Cancel Order
  📁 Users
     GET Get Profile
     PUT Update Profile

---

Creating a Collection

Method 1: From Scratch

  • Click + next to Collections
  • Name: Shop API
  • Add description
  • Click Create

Method 2: From Existing Requests

  • Click Save on any request
  • Choose + Create Collection
  • Name your collection

Adding Folders

Right-click collection → Add Folder

---

Collection Variables

Set variables at the collection level:

  • Click collection name
  • Go to Variables tab
  • Add variables:
VariableValue
baseUrlhttps://fakestoreapi.com
apiVersionv1

These are available to all requests in the collection.

---

Collection-Level Scripts

Pre-request Script (runs before EVERY request)

// Add timestamp to all requests
pm.collectionVariables.set("requestTime", new Date().toISOString());

// Add auth header if token exists
const token = pm.environment.get("authToken");
if (token) {
    pm.request.headers.add({
        key: "Authorization",
        value: `Bearer ${token}`
    });
}

Tests (runs after EVERY request)

// Log all responses
console.log("Response status:", pm.response.code);

// Common validations
pm.test("Response time is acceptable", function() {
    pm.expect(pm.response.responseTime).to.be.below(2000);
});

pm.test("No server errors", function() {
    pm.expect(pm.response.code).to.not.be.oneOf([500, 502, 503]);
});

---

Request Ordering

Setting Execution Order

Use Set Next Request to control flow:

// In Login request tests:
pm.test("Login successful", function() {
    if (pm.response.code === 200) {
        const response = pm.response.json();
        pm.environment.set("authToken", response.token);
        postman.setNextRequest("Get User Profile");
    } else {
        postman.setNextRequest(null); // Stop execution
    }
});

Conditional Flow

// Skip requests based on conditions
const cart = pm.response.json();

if (cart.items.length === 0) {
    console.log("Cart is empty, skipping checkout");
    postman.setNextRequest("Add to Cart");
} else {
    postman.setNextRequest("Checkout");
}

---

Collection Runner

Run all requests in sequence automatically!

Running a Collection

  • Click Run button on collection (or Runner in sidebar)
  • Select collection: Shop API
  • Choose environment: Development
  • Set iterations: 1 (or more for stress testing)
  • Click Run Shop API

Runner Options

OptionUse For
IterationsRun collection multiple times
DelayWait between requests (ms)
Data FileCSV/JSON for data-driven tests
Save ResponsesKeep responses for debugging

---

Data-Driven Testing

Test with multiple data sets using CSV or JSON files.

CSV File (products.csv)

productId,expectedName,expectedPrice
1,Fjallraven - Foldsack No. 1 Backpack,109.95
2,Mens Casual Premium Slim Fit T-Shirts,22.3
3,Mens Cotton Jacket,55.99

Request Using Data

GET {{baseUrl}}/products/{{productId}}

Tests Using Data

const response = pm.response.json();
const expectedName = pm.iterationData.get("expectedName");
const expectedPrice = pm.iterationData.get("expectedPrice");

pm.test("Product name matches", function() {
    pm.expect(response.title).to.equal(expectedName);
});

pm.test("Product price matches", function() {
    pm.expect(response.price).to.equal(parseFloat(expectedPrice));
});

Running with Data

  • Open Collection Runner
  • Select your collection
  • Click Select File → Choose products.csv
  • Run!

Each row in CSV = one iteration.

---

E-commerce Test Workflow

Complete Checkout Flow

Create this sequence:

  • Login → Save token
  • Get Products → Save first product ID
  • Add to Cart → Save cart ID
  • View Cart → Verify item added
  • Create Order → Save order ID
  • Get Order Status → Verify order created

Request Chain Example

1. Login Tests:
const response = pm.response.json();
pm.environment.set("authToken", response.token);
postman.setNextRequest("Get Products");
2. Get Products Tests:
const products = pm.response.json();
pm.environment.set("productId", products[0].id);
postman.setNextRequest("Add to Cart");
3. Add to Cart Tests:
const cart = pm.response.json();
pm.environment.set("cartId", cart.id);
postman.setNextRequest("View Cart");

---

Exporting Collections

Share your collection with the team:

  • Click on collection
  • Select Export
  • Choose format: Collection v2.1
  • Save file

Importing Collections

  • Click Import button
  • Drag & drop the JSON file
  • Click Import

---

Newman: Command Line Runner

Run collections from terminal for CI/CD integration.

Install Newman

npm install -g newman

Run Collection

# Basic run
newman run Shop_API.postman_collection.json

# With environment
newman run Shop_API.postman_collection.json -e Development.postman_environment.json

# With data file
newman run Shop_API.postman_collection.json -d products.csv

# Generate HTML report
newman run Shop_API.postman_collection.json -r html

CI/CD Integration

# GitHub Actions example
- name: Run API Tests
  run: |
    npm install -g newman
    newman run Shop_API.postman_collection.json \
      -e Production.postman_environment.json \
      --reporters cli,html \
      --reporter-html-export results.html

---

Monitors (Scheduled Runs)

Run collections on a schedule from Postman cloud:

  • Click on collection
  • Select Monitor collection
  • Configure:
- Frequency: Every hour / Every day

- Environment: Production

- Notifications: Email on failure

  • Click Create Monitor

Use for:

  • Production health checks
  • Uptime monitoring
  • Regression testing

---

Best Practices

1. Organize by Feature

📁 Products (all product operations)
📁 Cart (all cart operations)
📁 Orders (all order operations)

2. Name Requests Clearly

❌ Bad: Request 1, Test, New Request

✅ Good: GET Products by Category, POST Create Order

3. Add Descriptions

Document what each request does and expected behavior.

4. Use Folders for Test Types

📁 Smoke Tests (critical paths)
📁 Regression Tests (full coverage)
📁 Edge Cases (error handling)

---

Key Takeaways

FeaturePurpose
CollectionsOrganize related requests
FoldersGroup by feature/type
Collection RunnerRun all tests automatically
Data FilesTest with multiple inputs
NewmanCommand-line execution
MonitorsScheduled automated runs

You now have everything you need to build professional API test suites!

Next up: Quiz - test your API testing knowledge!

Environment Variables