Jump Into Our API Testing Adventure – $250 Prize + Swag for first 15 submissions

okay I will change this soon

Thank you for that challenge and for sharing some requests to use external packages.
Regarding my submission, I reused the cheerio npm package and reusable scripts.

//const jquery = pm.require('npm:[email protected]');
//const markup = pm.require('npm:[email protected]');
const aymarncommonUtils = pm.require('@postman-api-fundamentals-student-expert-6702/aymarncommon-utils');

const aymarncommonTests = pm.require('@postman-api-fundamentals-student-expert-6702/aymarncommon-tests');
var response = pm.response.text();

function testObject() {

    var cheerio = pm.require('npm:[email protected]');
    var $ = cheerio.load(response);
    var linksTab = [];
    var tabWithHttp = [];
    var text = "";

    links = $('#b_content').find('a'); //jquery get all hyperlinks
    $(links).each(function (i, link) {
        linksTab.push($(link).attr('href'));
    });

        function refactorTab(){
        
        for (var i in linksTab) {
            text = linksTab[i];
            
            result = /http/.test(text);
            if (result == true) {
                tabWithHttp.push(text);
            }
        }
        console.log(" *****tabWithHttp**** " + tabWithHttp)
        return tabWithHttp;
    }

    return { refactorTab}
}

var testObject = new testObject();
testObject.refactorTab();

pm.collectionVariables.set("links", JSON.stringify(testObject.refactorTab()));

var arrayLinks = pm.collectionVariables.get("links");
pm.test("Refactor Day 26 bing Array properly formatted", function () {

    pm.expect(arrayLinks.length).not.to.eql(0);
    pm.expect(arrayLinks.length).not.to.be.undefined;
    pm.expect(arrayLinks.length).not.to.be.NaN;

});

// A Package Library script that contains common assertions and checks for the response
//aymarncommonTests.basicAssertions();

// A Package Library script the contains common utility functions that can be individually used to create tests
//aymarncommonUtils.checkResponseTime();
aymarncommonUtils.checkStatusCode();

Again, thank you.

Hey Postman team! :waving_hand:

Here’s my entry for the API Testing Adventure Challenge.

Introducing: Smart API Diff Tester - A visual snapshot-based tool to monitor, validate, and highlight changes in your API responses over time.

What It Does?

  • It validates API structure using zod
  • Detects structural diffs using deep-diff
  • Checks for common contract violations (missing fields, type changes, etc.)
  • Stores a response snapshot and compares future responses against it
  • Visualizes changes with emoji-coded diff table
  • Warns if snapshot is stale (>30 mins)
  • Validates email & website using validator

External Packages Used

  • zod – schema validation
  • deep-diff – compare previous vs current response
  • date-fns – drift tracking (formatDistanceStrict)
  • validator – email & URL checks
  • pretty-bytes – readable sizes

How to Use

  • Import the collection and send any request returning structured JSON.
  • The test script will: Validate schema → compare against saved snapshot → Show diff summary in Visualizer → Re-send same request to check for drift

Sample Use Case

I tested against the jsonplaceholder fake API. Here’s the kind of output I get:

Schema :white_check_mark:
Email :white_check_mark:
Website :white_check_mark:
Diff :cross_mark: → warns me when something new is added (e.g. phone field)

Complete Post-response script

Script
//External packages
const { diff } = pm.require('npm:[email protected]');
const { z } = pm.require('npm:[email protected]');
const prettyBytes = pm.require('npm:[email protected]');
const { formatDistanceStrict, parseISO } = pm.require('npm:[email protected]');
const validator = pm.require('npm:[email protected]');

//Config
const strictMode = false;
const trackedFields = ["id", "name", "email", "website", "username", "address", "company"];
const snapshotVar = "snapshot_with_timestamp";
const driftThreshold = 30 * 60 * 1000;

//Helpers
function pick(obj, keys) {
  return Object.fromEntries(Object.entries(obj).filter(([k]) => keys.includes(k)));
}

function getSnapshot() {
  try {
    const raw = pm.collectionVariables.get(snapshotVar);
    return raw ? JSON.parse(raw) : null;
  } catch (e) {
    console.log("❌ Error parsing snapshot:", e);
    return null;
  }
}

function saveSnapshot(data) {
  pm.collectionVariables.set(snapshotVar, JSON.stringify({
    timestamp: new Date().toISOString(),
    data
  }));
}

//Actual logic
const currentFull = pm.response.json();
const current = trackedFields.length ? pick(currentFull, trackedFields) : currentFull;

/* to simulate deletions
delete current.username;
delete current.company.name; */

const savedSnapshot = getSnapshot();
const stored = savedSnapshot?.data || {};
const lastChecked = savedSnapshot?.timestamp || "Never";
const timeNow = new Date();
const timeThen = savedSnapshot ? parseISO(savedSnapshot.timestamp) : null;
const driftWarning = timeThen ? formatDistanceStrict(timeThen, timeNow) : "-";
const driftMs = timeThen ? timeNow - timeThen : 0;

const differences = diff(stored, current);

//Schema Validation
const schema = z.object({
  id: z.number(),
  name: z.string(),
  username: z.string(),
  email: z.string().email(),
  website: z.string().refine(val => validator.isURL(val, { require_protocol: false }), {
  message: "Invalid URL format"
}),

  address: z.object({
    street: z.string(),
    suite: z.string(),
    city: z.string(),
    zipcode: z.string(),
    geo: z.object({
      lat: z.string(),
      lng: z.string()
    })
  }),
  company: z.object({
    name: z.string(),
    catchPhrase: z.string(),
    bs: z.string()
  })
});

const zodResult = schema.safeParse(current);
saveSnapshot(current);

//Tests
pm.test("✅ Zod schema validation passed", () => zodResult.success);

pm.test("✅ No diff (structure match)", () => {
  if (strictMode) {
    pm.expect(differences, "Structure mismatch!").to.be.undefined;
  }
});

pm.test("✅ Email is valid", () => {
  pm.expect(validator.isEmail(current.email || "")).to.be.true;
});

pm.test("✅ Website is valid URL", () => {
  pm.expect(validator.isURL(current.website || "")).to.be.true;
});

//Visualizer helper
function prettifyDiff(diffArr) {
  if (!diffArr) return [];
  return diffArr.map(entry => {
    const kindEmoji = {
      N: "🟢 Added",
      D: "🔴 Deleted",
      E: "🟡 Edited",
      A: "🔵 Array"
    };
    return {
      kind: kindEmoji[entry.kind] || entry.kind,
      path: entry.path?.join(".") || "",
      oldValue: entry.lhs ?? "",
      newValue: entry.rhs ?? ""
    };
  });
}

const diffSummary = prettifyDiff(differences);

const changeCounts = {
  added: diffSummary.filter(d => d.kind === "🟢 Added").length,
  deleted: diffSummary.filter(d => d.kind === "🔴 Deleted").length,
  edited: diffSummary.filter(d => d.kind === "🟡 Edited").length,
  arrays: diffSummary.filter(d => d.kind === "🔵 Array").length
};

//Visualizer
pm.visualizer.set(`
  <style>
    body { font-family: sans-serif; padding: 10px; }
    table { width: 100%; border-collapse: collapse; margin-top: 12px; }
    th, td { border: 1px solid #ccc; padding: 8px; font-size: 14px; }
    th { background: #2b2b2b; color: #fff; }
    .kind-🟢 { background: #d4ffd4; }
    .kind-🔴 { background: #ffd6d6; }
    .kind-🟡 { background: #fff3cd; }
    .kind-🔵 { background: #d6ecff; }
  </style>

  <h2>🧪 Smart API Diff Tester</h2>
  <p><strong>📅 Last Snapshot:</strong> {{lastChecked}}</p>
  <p><strong>🕒 Drift Since:</strong> {{drift}}</p>

  {{#if diff.length}}
    <p style="color: orange;">⚠️ <strong>Differences Detected</strong></p>
    <ul>
      <li>🟢 Added: {{counts.added}}</li>
      <li>🔴 Deleted: {{counts.deleted}}</li>
      <li>🟡 Edited: {{counts.edited}}</li>
      <li>🔵 Array Changes: {{counts.arrays}}</li>
    </ul>
    <table>
      <tr><th>Type</th><th>Path</th><th>Old Value</th><th>New Value</th></tr>
      {{#each diff}}
        <tr class="kind-{{kind}}">
          <td>{{kind}}</td>
          <td>{{path}}</td>
          <td>{{oldValue}}</td>
          <td>{{newValue}}</td>
        </tr>
      {{/each}}
    </table>
  {{else}}
    <p style="color: green;">✅ No differences found. API is consistent.</p>
  {{/if}}

  <h3>📏 Schema Validation</h3>
  {{#if zodSuccess}}
    <p style="color: green;">✅ Schema passed</p>
  {{else}}
    <p style="color: red;">❌ Schema failed</p>
  {{/if}}
`, {
  diff: diffSummary,
  lastChecked,
  drift: driftWarning,
  zodSuccess: schema.safeParse(current).success,
  counts: changeCounts
});
if (!zodResult.success) {
  console.warn("❌ Zod Schema Errors:", zodResult.error.format());
}

Visuals




Happy testing!
Would love your feedback & support :raising_hands:

Here is the valid entry.

News API Headlines Fetcher — 24 Hour News Digest in Postman

:magnifying_glass_tilted_left: Overview:

This Postman workflow fetches the latest news headlines from the last 24 hours using the NewsAPI, processes the data, and presents it in both a plain-text summary and a clean HTML layout directly inside Postman’s Visualizer tab.

It’s a handy script for news monitoring, reporting dashboards, or daily summaries!

Pre-request Script

The script dynamically builds the request URL using:

  • moment.js to get the timestamp exactly 24 hours ago
  • Environment variable for NEWS_API_KEY
  • Query parameters to get English news sorted by most recent
const moment = pm.require('npm:moment');

console.log("📦 Loading Moment.js for date handling...");

// News API setup
const newsApiKey = pm.environment.get("NEWS_API_KEY") || "YOUR_API_KEY_HERE";
const baseUrl = "https://newsapi.org/v2/everything";

// Use moment.js to get date from 24 hours ago
const yesterday = moment().subtract(24, 'hours').toISOString();

console.log("📅 Fetching news from:", moment(yesterday).format('YYYY-MM-DD HH:mm'));

// Build the request URL
const requestUrl = `${baseUrl}?q=*&from=${yesterday}&language=en&sortBy=publishedAt&pageSize=20&apiKey=${newsApiKey}`;

// Set the request
pm.request.url = requestUrl;

console.log("🚀 Request URL ready:", requestUrl);

Post-Response Script

Once the API returns data:

  • It checks for a successful 200 OK response.
  • Processes the list of headlines (if any).
  • Generates:
    • :white_check_mark: A plain-text digest ({{news_headlines}})
    • :globe_with_meridians: A styled HTML layout ({{news_headlines_html}})
  • Renders the HTML using pm.visualizer.set().
console.log("📦 Processing headlines...");

const res = pm.response.json();

if (pm.response.code === 200 && res.status === "ok") {
    const articles = res.articles || [];
    const count = articles.length;
    const timestamp = new Date().toLocaleString();

    console.log(`✅ Found ${count} headlines`);

    // 📝 Plain text version
    const plainText = `📰 NEWS HEADLINES - LAST 24 HOURS\n` +
        `===============================\n\n` +
        articles.map((a, i) =>
            `${i + 1}. ${a.title}\n   Source: ${a.source.name}\n   URL: ${a.url}\n`
        ).join("\n") +
        `\nTotal Headlines: ${count}\nGenerated: ${timestamp}`;

    // 🌐 HTML version
    const html = `
<html>
<head>
  <title>News Headlines</title>
  <style>
    body { font-family: sans-serif; background: #f5f5f5; padding: 20px; }
    .box { background: #fff; padding: 20px; border-radius: 8px; max-width: 800px; margin: auto; }
    .headline { margin: 15px 0; border-left: 4px solid #007bff; padding-left: 10px; }
    .title { font-weight: bold; color: #333; }
    .source { color: #666; font-size: 14px; }
    .link { font-size: 14px; color: #007bff; text-decoration: none; }
  </style>
</head>
<body>
  <div class="box">
    <h2>📰 News Headlines (Last 24 Hours)</h2>
    <p>Total Headlines: ${count} | Updated: ${timestamp}</p>
    ${articles.map((a, i) => `
      <div class="headline">
        <div class="title">${i + 1}. ${a.title}</div>
        <div class="source">Source: ${a.source.name}</div>
        <a class="link" href="${a.url}" target="_blank">Read Article →</a>
      </div>`).join("")}
  </div>
</body>
</html>`.trim();

    // ✅ Save to environment
    pm.environment.set("news_headlines", plainText);
    pm.environment.set("news_headlines_html", html);
    pm.visualizer.set(html);


    // ✅ Log output
    console.log(plainText);
    console.log("🎉 Stored in {{news_headlines}} and {{news_headlines_html}}");

    // ✅ Tests
    pm.test("Fetched headlines", () => pm.expect(count).to.be.above(0));
    pm.test("Generated HTML", () => {
        pm.expect(html).to.include("<html>");
        pm.expect(html).to.include(articles[0].title);
    });

} else {
    console.error("❌ Failed to get headlines");
    pm.test("Request failed", () => pm.expect.fail("Could not fetch headlines"));
}

Key Features:

  • :stopwatch: Dynamic 24-hour date handling with Moment.js
  • :locked_with_key: Secure API key management using environment variables
  • :receipt: Text summary for logging or offline viewing
  • :nail_polish: HTML rendering via Postman Visualizer
  • :test_tube: Test assertions to ensure headline content is returned and parsed

This mini-project shows how Postman can go beyond testing — you can use it as a data processor, lightweight dashboard, or even a daily newsletter engine when combined with visualization and automation.

Today is your last chance to enter the latest Postman Community challenge!

We also still have a couple of spots still available (We opened up a few more) to win the Postman swag…you need to be quick though!! :rocket:

Submit something super cool using an external package from either npm or jsr and you could be taking home the $250 cash prize!! :trophy:

Thank you for your feedback.
I removed the reusable scripts and switched this to a Public Workspace.

var response = pm.response.text();

function testObject() {
    // Parse HTML
    var cheerio = pm.require('npm:[email protected]');
    var $ = cheerio.load(response);
    var linksTab = [];
    var tabWithHttp = [];
    var text = "";

    links = $('#b_content').find('a'); //jquery get all hyperlinks
    $(links).each(function (i, link) {
        linksTab.push($(link).attr('href'));
    });

        function refactorTab(){
        
        for (var i in linksTab) {
            text = linksTab[i];
            
            result = /http/.test(text);
            if (result == true) {
                tabWithHttp.push(text);
            }
        }
        console.log(" *****tabWithHttp**** " + tabWithHttp)
        return tabWithHttp;
    }

    return { refactorTab}
}

var testObject = new testObject();
testObject.refactorTab();

pm.collectionVariables.set("links", JSON.stringify(testObject.refactorTab()));

var arrayLinks = pm.collectionVariables.get("links");
pm.test("Refactor Day 26 bing Array properly formatted", function () {

    pm.expect(arrayLinks.length).not.to.eql(0);
    pm.expect(arrayLinks.length).not.to.be.undefined;
    pm.expect(arrayLinks.length).not.to.be.NaN;

});

I saw this feature request on the community asking how to compare two Postman collections and find new or changed endpoints.

I’ve been there. API collections get out of sync real fast, especially when working across teams or versions.

So… I built a thing!


:brain: What it does:

  • Compares two collections (old vs new)

  • Detects:

    • :white_check_mark: Unchanged endpoints
    • :counterclockwise_arrows_button: Modified endpoints (URL, headers, body, auth, etc.)
    • :inbox_tray: New endpoints
    • :cross_mark: Removed endpoints
  • Even suggests which folder new endpoints might belong to


:light_bulb: How it works:

Just drop your old collection into a global variable, hit the new one, and my test script runs the comparison.

It uses:

  • object-hash for unique endpoint signatures
  • fast-deep-equal to compare bodies/auth
  • lodash: Deep object comparison and array operations
  • Some basic HTML to show the results nicely in Postman

Code snippet

const hash = pm.require('npm:[email protected]');
const equal = pm.require('npm:[email protected]');
const _ = pm.require('npm:[email protected]');


pm.test("Collection Comparison and Analysis", function () {
    // Get collections (in real scenario, old collection would be stored in globals/environment)
    const oldCollection = JSON.parse(pm.globals.get("old_collection") || '{"item": []}');
    const newCollection = pm.response.json(); // New collection from API response
    
    // Perform comprehensive analysis
    const analysis = performCollectionAnalysis(oldCollection, newCollection);
    
    // Store results for visualization
    pm.globals.set("collection_analysis", JSON.stringify(analysis));
    
    // Log summary
    console.log("=== COLLECTION COMPARISON RESULTS ===");
    console.log(`📊 New endpoints: ${analysis.newEndpoints.length}`);
    console.log(`🔄 Modified endpoints: ${analysis.modifiedEndpoints.length}`);
    console.log(`✅ Unchanged endpoints: ${analysis.unchangedEndpoints}`);
    console.log(`❌ Removed endpoints: ${analysis.removedEndpoints.length}`);
    
    // Generate visualization
    generateVisualization(analysis);
});

function performCollectionAnalysis(oldCol, newCol) {
    console.log("🔍 Starting collection analysis...");
    
    // Extract and index old requests
    const oldRequests = new Map();
    const oldRequestsList = extractRequestsWithDetails(oldCol);
    
    oldRequestsList.forEach(req => {
        const signature = generateRequestSignature(req);
        oldRequests.set(signature, req);
    });
    
    // Analyze new requests
    const newRequestsList = extractRequestsWithDetails(newCol);
    const newEndpoints = [];
    const modifiedEndpoints = [];
    const unchangedEndpoints = [];
    
    newRequestsList.forEach(req => {
        const signature = generateRequestSignature(req);
        const oldReq = oldRequests.get(signature);
        
        if (!oldReq) {
            // Completely new endpoint
            newEndpoints.push({
                ...req,
                suggestedFolder: suggestFolderPlacement(req, newCol)
            });
        } else {
            // Check if request details changed
            const changes = findDetailedChanges(oldReq, req);
            if (changes.length > 0) {
                modifiedEndpoints.push({
                    ...req,
                    changes: changes,
                    oldVersion: oldReq
                });
            } else {
                unchangedEndpoints.push(req);
            }
            // Remove from old requests map
            oldRequests.delete(signature);
        }
    });
    
    // Remaining requests in oldRequests map are removed endpoints
    const removedEndpoints = Array.from(oldRequests.values());
    
    return {
        newEndpoints,
        modifiedEndpoints,
        unchangedEndpoints: unchangedEndpoints.length,
        removedEndpoints,
        summary: {
            totalOld: oldRequestsList.length,
            totalNew: newRequestsList.length,
            analysisTimestamp: new Date().toISOString()
        }
    };
}

function extractRequestsWithDetails(collection) {
    const requests = [];
    
    function traverseItems(items, folderPath = []) {
        if (!items) return;
        
        items.forEach(item => {
            if (item.request) {
                requests.push({
                    id: item.id || generateUniqueId(),
                    name: item.name,
                    method: item.request.method,
                    url: normalizeUrl(item.request.url),
                    headers: item.request.header || [],
                    body: item.request.body || {},
                    auth: item.request.auth || {},
                    folder: folderPath.join('/') || 'Root',
                    description: item.request.description || '',
                    tests: item.event?.filter(e => e.listen === 'test') || [],
                    prerequest: item.event?.filter(e => e.listen === 'prerequest') || []
                });
            }
            
            if (item.item) {
                traverseItems(item.item, [...folderPath, item.name]);
            }
        });
    }
    
    traverseItems(collection.item);
    return requests;
}

function generateRequestSignature(request) {
    // Create unique signature for request identification
    return hash({
        method: request.method,
        url: request.url,
        // Include headers that affect functionality, not just metadata
        // functionalHeaders: request.headers?.filter(h => 
        //     !['user-agent', 'postman-token'].includes(h.key?.toLowerCase())
        // ) || []
    });
}

function findDetailedChanges(oldReq, newReq) {
    const changes = [];
    
    // Check URL changes
    if (oldReq.url !== newReq.url) {
        changes.push(`URL changed from '${oldReq.url}' to '${newReq.url}'`);
    }
    
    // Check header changes
    const oldHeaders = _.keyBy(oldReq.headers || [], 'key');
    const newHeaders = _.keyBy(newReq.headers || [], 'key');
    
    Object.keys(newHeaders).forEach(key => {
        if (!oldHeaders[key]) {
            changes.push(`Added header: ${key}`);
        } else if (oldHeaders[key].value !== newHeaders[key].value) {
            changes.push(`Modified header '${key}': ${oldHeaders[key].value} → ${newHeaders[key].value}`);
        }
    });
    
    Object.keys(oldHeaders).forEach(key => {
        if (!newHeaders[key]) {
            changes.push(`Removed header: ${key}`);
        }
    });
    
    // Check body changes
    if (!equal(oldReq.body, newReq.body)) {
        if (oldReq.body?.raw !== newReq.body?.raw) {
            changes.push("Request body modified");
        }
        if (oldReq.body?.mode !== newReq.body?.mode) {
            changes.push(`Body mode changed: ${oldReq.body?.mode} → ${newReq.body?.mode}`);
        }
    }
    
    // Check auth changes
    if (!equal(oldReq.auth, newReq.auth)) {
        changes.push("Authentication configuration changed");
    }
    
    // Check test changes
    if (oldReq.tests?.length !== newReq.tests?.length) {
        changes.push(`Test count changed: ${oldReq.tests?.length || 0} → ${newReq.tests?.length || 0}`);
    }
    
    return changes;
}

function suggestFolderPlacement(request, collection) {
    // Intelligent folder suggestion based on URL patterns
    const url = request.url.toLowerCase();
    
    if (url.includes('/auth') || url.includes('/login') || url.includes('/token')) {
        return 'Authentication';
    } else if (url.includes('/user') || url.includes('/profile')) {
        return 'User Management';
    } else if (url.includes('/product') || url.includes('/catalog')) {
        return 'Products';
    } else if (url.includes('/order') || url.includes('/purchase')) {
        return 'Orders';
    } else if (url.includes('/admin') || url.includes('/management')) {
        return 'Administration';
    } else if (url.includes('/report') || url.includes('/analytics')) {
        return 'Reporting';
    } else {
        // Try to match existing folder structure
        const existingFolders = extractFolderNames(collection);
        const urlParts = request.url.split('/').filter(part => part && !part.match(/^v\d+$/));
        
        for (const folder of existingFolders) {
            for (const part of urlParts) {
                if (folder.toLowerCase().includes(part.toLowerCase()) || 
                    part.toLowerCase().includes(folder.toLowerCase())) {
                    return folder;
                }
            }
        }
        
        return 'General';
    }
}

function extractFolderNames(collection) {
    const folders = new Set();
    
    function traverse(items) {
        if (!items) return;
        items.forEach(item => {
            if (item.item) {
                folders.add(item.name);
                traverse(item.item);
            }
        });
    }
    
    traverse(collection.item);
    return Array.from(folders);
}

function normalizeUrl(url) {
    if (typeof url === 'string') return url.trim();

    if (url?.raw) return url.raw.trim();

    if (url?.host && url?.path) {
        const host = Array.isArray(url.host) ? url.host.join('.') : url.host;
        const path = Array.isArray(url.path) ? '/' + url.path.join('/') : url.path;
        return `${host}${path}`.trim();
    }

    return '';
}


function generateUniqueId() {
    return 'req_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

function generateVisualization(analysis) {
    const template = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Collection Comparison Dashboard</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                padding: 20px;
                color: #333;
            }

            .dashboard {
                max-width: 1400px;
                margin: 0 auto;
                background: rgba(255, 255, 255, 0.95);
                border-radius: 20px;
                box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
                overflow: hidden;
                backdrop-filter: blur(10px);
            }

            .header {
                background: linear-gradient(135deg, #ff6b6b, #feca57);
                padding: 30px;
                text-align: center;
                color: white;
            }

            .header h1 {
                font-size: 2.5rem;
                margin-bottom: 10px;
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            }

            .stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
                gap: 20px;
                padding: 30px;
                background: #f8f9fa;
            }

            .stat-card {
                background: white;
                padding: 25px;
                border-radius: 15px;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
                border-left: 5px solid;
                transition: transform 0.3s ease;
            }

            .stat-card:hover {
                transform: translateY(-5px);
            }

            .stat-card.new { border-left-color: #27ae60; }
            .stat-card.modified { border-left-color: #f39c12; }
            .stat-card.unchanged { border-left-color: #3498db; }
            .stat-card.removed { border-left-color: #e74c3c; }

            .stat-number {
                font-size: 3rem;
                font-weight: bold;
                margin-bottom: 10px;
            }

            .stat-card.new .stat-number { color: #27ae60; }
            .stat-card.modified .stat-number { color: #f39c12; }
            .stat-card.unchanged .stat-number { color: #3498db; }
            .stat-card.removed .stat-number { color: #e74c3c; }

            .content-section {
                padding: 30px;
            }

            .endpoint-list {
                margin-top: 20px;
            }

            .endpoint-item {
                display: flex;
                align-items: center;
                padding: 15px;
                margin-bottom: 10px;
                border-radius: 10px;
                transition: all 0.3s ease;
                border-left: 4px solid;
            }

            .endpoint-item.new { 
                background: #d5f4e6; 
                border-left-color: #27ae60; 
            }
            .endpoint-item.modified { 
                background: #fef9e7; 
                border-left-color: #f39c12; 
            }
            .endpoint-item.removed { 
                background: #fadbd8; 
                border-left-color: #e74c3c; 
            }

            .method-badge {
                padding: 5px 12px;
                border-radius: 20px;
                font-size: 0.8rem;
                font-weight: bold;
                margin-right: 15px;
                min-width: 60px;
                text-align: center;
                color: white;
            }

            .method-get { background: #27ae60; }
            .method-post { background: #f39c12; }
            .method-put { background: #3498db; }
            .method-delete { background: #e74c3c; }
            .method-patch { background: #9b59b6; }

            .endpoint-details {
                flex: 1;
            }

            .endpoint-name {
                font-weight: 600;
                margin-bottom: 5px;
                color: #2c3e50;
            }

            .endpoint-url {
                font-size: 0.9rem;
                color: #666;
                font-family: 'Monaco', 'Courier New', monospace;
                margin-bottom: 5px;
            }

            .changes-list {
                margin-top: 8px;
            }

            .change-item {
                font-size: 0.8rem;
                color: #666;
                margin-bottom: 3px;
                padding-left: 15px;
                position: relative;
            }

            .change-item:before {
                content: "•";
                position: absolute;
                left: 0;
                color: #f39c12;
            }

            .section-title {
                font-size: 1.3rem;
                font-weight: 600;
                margin-bottom: 15px;
                color: #2c3e50;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .empty-state {
                text-align: center;
                padding: 40px 20px;
                color: #666;
                font-style: italic;
            }

            .merge-summary {
                background: #e8f5e8;
                border: 1px solid #27ae60;
                border-radius: 10px;
                padding: 20px;
                margin: 20px 0;
            }

            .timestamp {
                text-align: center;
                padding: 20px;
                color: #666;
                font-size: 0.9rem;
                background: #f8f9fa;
                border-top: 1px solid #dee2e6;
            }
        </style>
    </head>
    <body>
        <div class="dashboard">
            <div class="header">
                <h1>🔄 Collection Comparison Dashboard</h1>
             
            </div>

            <div class="stats-grid">
                <div class="stat-card new">
                    <div class="stat-number">${analysis.newEndpoints.length}</div>
                    <div class="stat-label">New Endpoints</div>
                    <div class="stat-description">Ready to be added</div>
                </div>
                <div class="stat-card modified">
                    <div class="stat-number">${analysis.modifiedEndpoints.length}</div>
                    <div class="stat-label">Modified Endpoints</div>
                    <div class="stat-description">Require updates</div>
                </div>
                <div class="stat-card unchanged">
                    <div class="stat-number">${analysis.unchangedEndpoints}</div>
                    <div class="stat-label">Unchanged Endpoints</div>
                    <div class="stat-description">No action needed</div>
                </div>
                <div class="stat-card removed">
                    <div class="stat-number">${analysis.removedEndpoints.length}</div>
                    <div class="stat-label">Removed Endpoints</div>
                    <div class="stat-description">Missing in new collection</div>
                </div>
            </div>

            <div class="content-section">
                ${generateNewEndpointsSection(analysis.newEndpoints)}
                ${generateModifiedEndpointsSection(analysis.modifiedEndpoints)}
                ${generateRemovedEndpointsSection(analysis.removedEndpoints)}
                ${generateMergeSummary(analysis)}
            </div>

            <div class="timestamp">
                Analysis completed at: ${new Date(analysis.summary.analysisTimestamp).toLocaleString()}
                <br>
                Old Collection: ${analysis.summary.totalOld} endpoints | 
                New Collection: ${analysis.summary.totalNew} endpoints
            </div>
        </div>
    </body>
    </html>
    `;

    pm.visualizer.set(template);
}

function generateNewEndpointsSection(newEndpoints) {
    if (newEndpoints.length === 0) {
        return `
            <div class="section-title">✨ New Endpoints</div>
            <div class="empty-state">No new endpoints detected</div>
        `;
    }

    const endpointsHtml = newEndpoints.map(endpoint => `
        <div class="endpoint-item new">
            <div class="method-badge method-${endpoint.method.toLowerCase()}">${endpoint.method}</div>
            <div class="endpoint-details">
                <div class="endpoint-name">${endpoint.name}</div>
                <div class="endpoint-url">${endpoint.url}</div>
                <div style="font-size: 0.8rem; color: #666; margin-top: 5px;">
                    📁 Suggested folder: ${endpoint.suggestedFolder}
                </div>
            </div>
        </div>
    `).join('');

    return `
        <div class="section-title">✨ New Endpoints (${newEndpoints.length})</div>
        <div class="endpoint-list">${endpointsHtml}</div>
    `;
}

function generateModifiedEndpointsSection(modifiedEndpoints) {
    if (modifiedEndpoints.length === 0) {
        return `
            <div class="section-title">⚡ Modified Endpoints</div>
            <div class="empty-state">No modifications detected</div>
        `;
    }

    const endpointsHtml = modifiedEndpoints.map(endpoint => {
        const changesHtml = endpoint.changes.map(change => 
            `<div class="change-item">${change}</div>`
        ).join('');

        return `
            <div class="endpoint-item modified">
                <div class="method-badge method-${endpoint.method.toLowerCase()}">${endpoint.method}</div>
                <div class="endpoint-details">
                    <div class="endpoint-name">${endpoint.name}</div>
                    <div class="endpoint-url">${endpoint.url}</div>
                    <div class="changes-list">
                        <strong>Changes detected:</strong>
                        ${changesHtml}
                    </div>
                </div>
            </div>
        `;
    }).join('');

    return `
        <div class="section-title">⚡ Modified Endpoints (${modifiedEndpoints.length})</div>
        <div class="endpoint-list">${endpointsHtml}</div>
    `;
}

function generateRemovedEndpointsSection(removedEndpoints) {
    if (removedEndpoints.length === 0) {
        return `
            <div class="section-title">❌ Removed Endpoints</div>
            <div class="empty-state">No endpoints were removed</div>
        `;
    }

    const endpointsHtml = removedEndpoints.map(endpoint => `
        <div class="endpoint-item removed">
            <div class="method-badge method-${endpoint.method.toLowerCase()}">${endpoint.method}</div>
            <div class="endpoint-details">
                <div class="endpoint-name">${endpoint.name}</div>
                <div class="endpoint-url">${endpoint.url}</div>
                <div style="font-size: 0.8rem; color: #666; margin-top: 5px;">
                    ⚠️ Consider archiving or removing from collection
                </div>
            </div>
        </div>
    `).join('');

    return `
        <div class="section-title">❌ Removed Endpoints (${removedEndpoints.length})</div>
        <div class="endpoint-list">${endpointsHtml}</div>
    `;
}

function generateMergeSummary(analysis) {
    const total = analysis.newEndpoints.length + analysis.modifiedEndpoints.length + 
                  analysis.unchangedEndpoints + analysis.removedEndpoints.length;
    
    const actionItems = [];
    
    if (analysis.newEndpoints.length > 0) {
        actionItems.push(`Add ${analysis.newEndpoints.length} new endpoint${analysis.newEndpoints.length > 1 ? 's' : ''}`);
    }
    
    if (analysis.modifiedEndpoints.length > 0) {
        actionItems.push(`Update ${analysis.modifiedEndpoints.length} modified endpoint${analysis.modifiedEndpoints.length > 1 ? 's' : ''}`);
    }
    
    if (analysis.removedEndpoints.length > 0) {
        actionItems.push(`Review ${analysis.removedEndpoints.length} removed endpoint${analysis.removedEndpoints.length > 1 ? 's' : ''}`);
    }

    const actionText = actionItems.length > 0 ? actionItems.join(', ') : 'No actions required';

    return `
        <div class="merge-summary">
            <div class="section-title">📋 Merge Summary</div>
            <p><strong>Total endpoints analyzed:</strong> ${total}</p>
            <p><strong>Actions required:</strong> ${actionText}</p>
            <p><strong>Collection sync status:</strong> ${
                analysis.newEndpoints.length === 0 && analysis.modifiedEndpoints.length === 0 && analysis.removedEndpoints.length === 0
                    ? '✅ Collections are in sync'
                    : '🔄 Manual merge required'
            }</p>
        </div>
    `;
}

:bar_chart: Output looks like this:

📊 New endpoints: 3  
🔄 Modified endpoints: 2  
✅ Unchanged endpoints: 5  
❌ Removed endpoints: 1  

With a breakdown of exactly what changed — header diffs, body changes, all of it.



Wild how a few packages inside a script can turn a feature request into a working tool. Didn’t expect it to be this smooth!

This script fetches a random user from the Random User API and uses the moment NPM package to format and display the user’s registration date in a readable format, showing when they joined and how long ago that was.

const moment = pm.require('npm:[email protected]');
// Parse the JSON response
const data = pm.response.json();

// Get user's registration date
const registeredDate = data.results[0].registered.date;

// Format the date using moment
const formattedDate = moment(registeredDate).format("MMMM Do YYYY, h:mm:ss a");

// Display info in Postman Console
console.log("👤 User Registered On (Raw):", registeredDate);
console.log("🗓️ Formatted with Moment:", formattedDate);

// Example test
pm.test("User registration date is present and formatted", () => {
    pm.expect(registeredDate).to.be.a('string');
    pm.expect(formattedDate).to.include(',');
});

I created a request called Chance User Generator in my fork of the workspace “June Challenge”. I used the chance.js library to generate random test data like names, titles, and user IDs during the Pre-request Script.

It is perfect for load testing and simulating real users.

Pre-request:

const chance = pm.require('npm:[email protected]');
const ch = new chance.Chance();
const randomTitle = ch.sentence({ words: 5 });
const randomUserId = ch.integer({ min: 1, max: 10 });
pm.collectionVariables.set("randomTitle", randomTitle);
pm.collectionVariables.set("randomUserId", randomUserId);

Post-response to test it:

pm.test("Random data present in query params", () => {
    const args = pm.response.json().args;
    pm.expect(args.title).to.be.a("string").and.not.empty;
    pm.expect(Number(args.userId)).to.be.within(1, 10);
});

POST method to get the query params:

pm.test("Random data present in query params", () => {
    const args = pm.response.json().args;

    console.log("Echoed query params:", args);

    pm.expect(args.title, "title param missing").to.be.a("string").and.not.empty;
    pm.expect(parseInt(args.userId), "userId param missing or invalid").to.be.within(1, 10);
});

Please checkout my workspace !! :slightly_smiling_face:

The must-do update on the actions: Adding the integration with AI :sparkles: and visualisation features.

Script session

Can be putt in collection scope, so it replicates effortless through out all your requests.

Pre-request:

const QUICKY_ACTIONS = {
    'X-QUICKY-COMPARE-RES-HASH': () => {
        const CURRENT_HASH = pm.collectionVariables.get(`QUICKY_RES_HASH_${pm.info.requestId}`);
        if (!CURRENT_HASH) throw new Error('QUICKY ERROR: Initial hash not setted, run with X-QUICKY-UPDATE-RES-HASH header')
        const RESPONSE_HASH = getHash(JSON.stringify(pm.response.json()));
        pm.test('QUICKY_AUTO - COMPARE RESPONSE HASH', () => { pm.expect(CURRENT_HASH).to.be.eq(RESPONSE_HASH); })
    },
    'X-QUICKY-UPDATE-RES-HASH': () => {
        pm.collectionVariables.set(`QUICKY_RES_HASH_${pm.info.requestId}`, getHash(JSON.stringify(pm.response.json())));
        pm.test("QUICKY_AUTO - SAVE RESPONSE HASH", () => pm.expect(true));
    },
    'X-QUICKY-VALIDATE-RES-SCHEMA': () => {
        const CURRENT_SCHEMA = eval(pm.collectionVariables.get(`QUICKY_RES_SCHEMA_${pm.info.requestId}`));
        if (!CURRENT_SCHEMA) throw new Error('QUICKY ERROR: Initial schema not setted, run with X-QUICKY-UPDATE-RES-SCHEMA header')
        pm.test('QUICKY_AUTO - VALIDATE RESPONSE SCHEMA', () => {
            try {
                const parsedData = CURRENT_SCHEMA.parse(pm.response.json());
                pm.expect(parsedData).to.be.an('object');
            } catch (error) {
                console.error("Validation errors:", error);
                pm.expect(error.errors).to.be.empty()
            }
        })
    },
    'X-QUICKY-UPDATE-RES-SCHEMA': () => {
        const rawZodString = jsonToZod(pm.response.json());
        const wrapped = `(function() {
            ${rawZodString}
            return schema;
        })()`;

        pm.collectionVariables.set(`QUICKY_RES_SCHEMA_${pm.info.requestId}`, wrapped);
        pm.test('QUICKY_AUTO - SAVE RESPONSE SCHEMA', () => pm.expect(true));
    },
    'X-QUICKY-UPDATE-AI-TESTS': () => {
        const ANTHROPIC_API_KEY = pm.collectionVariables.get("QUICKY_ANTHROPIC_APIKEY");
        const requestId = pm.info.requestId;
        const responseBody = pm.response.json();

        if (!ANTHROPIC_API_KEY) {
            throw new Error("QUICKY ERROR: Missing QUICKY_ANTHROPIC_APIKEY");
        }

        const prompt = `
You are a Postman automation assistant. Generate JavaScript tests using pm.test() for the following API response:
Respond with only valid pm.test(...) code — do not include explanations (MAX 2000 characters).

API response:
${JSON.stringify(responseBody, null, 2)}
`;

        pm.sendRequest({
            url: 'https://api.anthropic.com/v1/messages',
            method: 'POST',
            header: {
                'Content-Type': 'application/json',
                'anthropic-version': '2023-06-01',
                'x-api-key': `${ANTHROPIC_API_KEY}`
            },
            body: {
                mode: 'raw',
                raw: JSON.stringify({
                    model: "claude-opus-4-20250514",
                    max_tokens: 1024,
                    messages: [
                        { role: 'user', content: prompt }
                    ],
                    temperature: 0.2,
                    max_tokens: 800
                })
            }
        }, (err, res) => {
            if (err) {
                console.error("Anthropic request failed:", err);
                throw new Error("QUICKY ERROR: Failed to contact Anthropic API.");
            }

            let aiScript = res.json()?.content?.[0]?.text || '';

            if (!aiScript || !aiScript.includes("pm.test")) {
                console.error("Invalid response from Anthropic:", res.json());
                throw new Error("QUICKY ERROR: AI did not return valid pm.test code.");
            }

            aiScript = aiScript.trim();
            if (aiScript.startsWith('```')) {
                aiScript = aiScript.replace(/^```(?:javascript)?\n?/i, '').replace(/```$/, '').trim();
            }

            aiScript = aiScript.replace(/pm\.test\(\s*["'`](.*?)(["'`])\s*,/g, (match, name) => {
                const newName = name.startsWith("QUICKY_AI - ") ? name : `QUICKY_AI - ${name}`;
                return `quicky.test("${newName}",`;
            });

            // Store result in collection variable
            pm.collectionVariables.set(`QUICKY_AI_TESTS_${requestId}`, aiScript);

            console.log("✅ AI test generated and stored.");
            console.log(aiScript);

            pm.test('QUICKY_AUTO - AI test generated successfully', () => {
                pm.expect(aiScript).to.include("quicky.test");
            });
        });
    },

    'X-QUICKY-RUN-AI-TESTS': () => {
        const aiCode = pm.collectionVariables.get(`QUICKY_AI_TESTS_${pm.info.requestId}`);

        if (!aiCode) {
            throw new Error("QUICKY ERROR: No AI-generated tests found for this request.");
        }

        try {
            eval(aiCode);
        } catch (err) {
            console.error("Execution error:", err);
            throw new Error("QUICKY ERROR: AI-generated tests failed to run.");
        }
    }

}


pm.collectionVariables.set('QUICKY_TEST_RESULTS', JSON.stringify([]));

const addTestResult = (name, passed, isAI = false) => {
    const current = JSON.parse(pm.collectionVariables.get('QUICKY_TEST_RESULTS') || '[]');
    current.push({ name, passed, isAI });
    pm.collectionVariables.set('QUICKY_TEST_RESULTS', JSON.stringify(current));
};

const QUICKY_HEADERS = Object.keys(QUICKY_ACTIONS)

// Default actions
const QUICKY_DEFAULT_ACTIONS = JSON.parse(pm.collectionVariables.get('QUICKY_DEFAULT_ACTIONS') ?? [])

QUICKY_DEFAULT_ACTIONS.forEach((header) => {
    pm.request.addHeader({ key: header })
})

const ACTIVE_FLAGS = (pm.request.headers ?? []).filter(header => !header.disabled).map(header => header.key)

const ACTIONS_FLAGS = QUICKY_HEADERS.map(header => ({key: header, active: ACTIVE_FLAGS.includes(header)}))

const QUICKY_AUTO_ACTIONS = ACTIVE_FLAGS.filter((action) => action && QUICKY_ACTIONS[action]).map((action) => String(QUICKY_ACTIONS[action]))

pm.collectionVariables.set('QUICKY_AUTO_ACTIONS', JSON.stringify({flags: ACTIONS_FLAGS, actions: QUICKY_AUTO_ACTIONS}))

// Remove all X-QUICKY header
QUICKY_HEADERS.forEach((header) => {
    pm.request.removeHeader(header)
})

Post-request:

const { z } = pm.require('npm:[email protected]');
const { jsonToZod } = pm.require('npm:[email protected]');
const crypto = pm.require('npm:[email protected]')

const getHash = (text) => crypto.MD5(text).toString()

const QUICKY_RESULTS = [];
const originalPmTest = pm.test;
const quicky = {test: function(name, fn) {
    try {
        pm.test(name, fn()); // Run the test
        console.log(name)
        QUICKY_RESULTS.push({ name, passed: true, isAI: name.startsWith("QUICKY_AI - ") });
    } catch (err) {
        QUICKY_RESULTS.push({ name, passed: false, isAI: name.startsWith("QUICKY_AI - ") });
        throw err;
    }
}};


const {flags: QUICKY_FLAGS, actions: QUICKY_ACTIONS} = JSON.parse(pm.collectionVariables.get("QUICKY_AUTO_ACTIONS").replace(/pm\.test/g, () => 'quicky.test'))

console.log(QUICKY_ACTIONS)
QUICKY_ACTIONS.forEach((action) => {
    try {
        const funct = eval(action)
        funct()
    } catch (error) {
        console.log(error)
    }
})

QUICKY_RESULTS.sort((a, b) => {
    if (a.isAI && !b.isAI) return 1;
    if (!a.isAI && b.isAI) return -1;
    return a.name.localeCompare(b.name);
});

pm.visualizer.set(`
<style>
  body {
    background-color: #1e1e1e;
    font-family: "Segoe UI", Roboto, sans-serif;
    color: #d4d4d4;
    padding: 20px;
  }
  h2 {
    color: #ff6b6b;
    border-bottom: 2px solid #333;
    padding-bottom: 5px;
    margin-bottom: 10px;
  }
  .section {
    margin-bottom: 30px;
  }
  .badge {
    display: inline-block;
    background-color: #262626;
    color: #ffaa00;
    border: 1px solid #333;
    padding: 5px 10px;
    margin: 3px;
    border-radius: 6px;
    font-size: 0.9em;
  }
  .test-result {
    background-color: #2d2d2d;
    border-left: 4px solid;
    border-color: #00c46b;
    padding: 10px;
    margin: 8px 0;
    border-radius: 6px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .test-result.failed {
    border-color: #ff5c5c;
  }
  .test-result span {
    flex: 1;
    color: #ddd;
  }
  .status {
    font-weight: bold;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 0.85em;
  }
  .passed .status {
    background-color: #00c46b;
    color: #1e1e1e;
  }
  .failed .status {
    background-color: #ff5c5c;
    color: #1e1e1e;
  }
</style>

<div class="section">
  <h2>🧩 Flags Active</h2>
  {{#if flags.length}}
    {{#each flags}}<span class="badge">{{this}}</span>{{/each}}
  {{else}}
    <p>No QUICKY flags were active for this request.</p>
  {{/if}}
</div>

<div class="section">
  <h2>📊 Results</h2>
  {{#each results}}
    <div class="test-result {{#unless passed}}failed{{/unless}}">
      <span>{{name}}</span>
      <span class="status">{{#if passed}}PASSED{{else}}FAILED{{/if}}</span>
    </div>
  {{/each}}
</div>
`, {
    flags: QUICKY_FLAGS.filter(h => h.active).map(h=>h.key),
    results: QUICKY_RESULTS
});

Results

The cool part is: You just have to put this pre and post scripts in your collection level and add the necessary headers to make it work for each and every API project :sparkles:.

Hey everyone,

The June Community Challenge has now ended! :checkered_flag:

I wanted to just say a huge thank you to everyone who joined in and made this challenge awesome, the submissions have been incredible!!

What’s next?

  • We’re reviewing all valid entries. The first 25 eligible submissions, will be receiving Postman swag.

  • We’ll also be selecting the winner of the $250 grand prize.

All swag recipients will receive a DM from us and the grand prize winner will be announced by the end of the week.

Thanks again!! If you missed out this time, don’t worry as we’ll be back with another challenge very soon!!

June Challenge Winner:

We’re excited to announce the winner of the June API Testing Adventure Challenge. Congratulations to @abdulkabirsultan for their outstanding Article/Text Analyzer project.

This submission stood out for its clear documentation, practical utility, and thoughtful use of Postman features like the Console and Visualizer. It also introduced external modules—franc, sentiment, and node-summary—that added extra functionality beyond the base challenge.

Thanks to everyone who participated. Our next challenge is coming soon :eyes:. Keep building, keep sharing, and stay curious.