0
0
Postmantesting~15 mins

Monitor regions in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify Postman Monitor runs successfully in specified regions
Preconditions (2)
Step 1: Log in to Postman web dashboard
Step 2: Navigate to the Monitors section
Step 3: Create a new monitor for the given collection
Step 4: Select multiple regions (e.g., US East, Europe, Asia) for the monitor to run
Step 5: Save and start the monitor
Step 6: Wait for the monitor to complete at least one run
Step 7: Open the monitor run results
Step 8: Verify that the monitor ran successfully in all selected regions
✅ Expected Result: The monitor runs successfully in all selected regions and the run results show status 'Passed' for each region.
Automation Requirements - Postman API with Newman and Node.js
Assertions Needed:
Verify monitor creation response status is 201
Verify monitor run status is 'completed'
Verify each selected region has a successful run status
Verify no errors in monitor run results
Best Practices:
Use Postman API to create and manage monitors programmatically
Use Newman to run collections locally for validation
Use explicit checks on API responses and run results
Handle asynchronous waits for monitor run completion
Use environment variables for region names and monitor IDs
Automated Solution
Postman
import fetch from 'node-fetch';

const API_KEY = process.env.POSTMAN_API_KEY;
const COLLECTION_UID = process.env.COLLECTION_UID;
const MONITOR_NAME = 'Test Monitor Regions';
const REGIONS = ['us-east-1', 'eu-west-1', 'ap-southeast-1'];

async function createMonitor() {
  const url = 'https://api.getpostman.com/monitors';
  const body = {
    monitor: {
      name: MONITOR_NAME,
      collection: {
        uid: COLLECTION_UID
      },
      environment: null,
      schedule: {
        type: 'interval',
        interval: 5,
        unit: 'minutes'
      },
      regions: REGIONS
    }
  };

  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'X-Api-Key': API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  });

  if (response.status !== 201) {
    throw new Error(`Failed to create monitor: ${response.status}`);
  }

  const data = await response.json();
  return data.monitor.id;
}

async function waitForMonitorRun(monitorId) {
  const url = `https://api.getpostman.com/monitors/${monitorId}/runs`;
  let attempts = 0;
  while (attempts < 20) {
    const response = await fetch(url, {
      headers: { 'X-Api-Key': API_KEY }
    });
    if (response.status !== 200) {
      throw new Error(`Failed to get monitor runs: ${response.status}`);
    }
    const data = await response.json();
    if (data.runs && data.runs.length > 0) {
      const latestRun = data.runs[0];
      if (latestRun.status === 'completed') {
        return latestRun;
      }
    }
    await new Promise(r => setTimeout(r, 15000));
    attempts++;
  }
  throw new Error('Monitor run did not complete in time');
}

function verifyRegions(run) {
  const runRegions = run.regions || [];
  for (const region of REGIONS) {
    const regionRun = runRegions.find(r => r.region === region);
    if (!regionRun) {
      throw new Error(`No run data for region: ${region}`);
    }
    if (regionRun.status !== 'passed') {
      throw new Error(`Region ${region} run failed with status: ${regionRun.status}`);
    }
  }
}

(async () => {
  try {
    const monitorId = await createMonitor();
    console.log(`Monitor created with ID: ${monitorId}`);

    const run = await waitForMonitorRun(monitorId);
    console.log('Monitor run completed');

    verifyRegions(run);
    console.log('All regions passed successfully');
  } catch (error) {
    console.error('Test failed:', error.message);
    process.exit(1);
  }
})();

This script uses the Postman API to create a monitor with specified regions. It sends a POST request with the monitor details including the collection UID and the regions array.

After creation, it polls the monitor runs endpoint every 15 seconds up to 5 minutes to wait for a completed run.

Once a run is completed, it verifies that each selected region has a run status of 'passed'. If any region is missing or failed, it throws an error.

This approach uses explicit waits and checks API responses carefully, following best practices for asynchronous operations and API testing.

Common Mistakes - 4 Pitfalls
Hardcoding API keys directly in the script
Not waiting for the monitor run to complete before checking results
Assuming monitor runs return region data without checking
Using synchronous waits like sleep without async handling
Bonus Challenge

Now add data-driven testing with 3 different sets of regions to verify monitor runs in multiple region combinations

Show Hint