Postman Collection SDK

repository·develop·Indexed 19 days ago

https://github.com/postmanlabs/postman-collection

A NodeJS module for the programmatic manipulation of Postman Collections. It enables developers to create, modify, and export collections in formats natively consumable by Postman Apps and CLI runtimes like Newman. The SDK provides tools for managing the collection hierarchy (Collections, ItemGroups, and Items), configuring Request objects, handling lifecycle events (pre-request and test scripts), and implementing mutation tracking for state transitions.

Tokens
8.5K
Snippets
36
Records
40
Agent score
66%

What's inside postman-collection

  1. Understand the Postman Collection hierarchy

    develop

    Postman Collections are organized in a hierarchical structure. At the top level is a Collection, which contains an information block and an array of items. These items can be either Items (the basic building block representing an HTTP request) or ItemGroups (folders used to containerize other Items or ItemGroups).

    Hierarchy Summary:

    • Collection: The root container. Contains information and items.
    • ItemGroup (Folder): A container for Items or other ItemGroups.
    • Item: Represents an HTTP request and its metadata. Can contain responses and events.
    • Request: The actual HTTP definition (URL, method, headers, body, auth) usually contained within an Item.
    • Events: Scripts associated with an Item that run at specific lifecycle stages (e.g., prerequest or test).
  2. How mutation tracking works in Postman Collection SDK

    develop

    Mutation tracking captures state transitions of an object as a sequence of serializable objects. This allows you to record individual changes (like set, unset, or clear operations) and replay them on a different object to achieve mirroring or to observe intermediate states.

    The system relies on two main components:

    1. Mutation: An individual, serializable change that captures a single update. It follows a JSON Delta-based specification where the instruction (e.g., set vs unset) is derived from the number of parameters in the array.
    2. MutationTracker: A component that collects a sequence of mutations, provides helpers to apply them to new objects, and can optimize the sequence (e.g., via compression).

    Mutation Representation

    Mutations are represented as arrays where the instruction is implicit:

    • Set operation: ['keyPath', value] (two parameters)
    • Unset operation: ['keyPath'] (one parameter)

    Example of a set operation: ['foo', 1] where 'foo' is the Key Path and 1 is the Value applied to the Target object.

  3. Use Events (Pre-request and Test scripts) in an Item

    develop

    You can associate scripts with an Item using the event array. The SDK supports two primary event types:

    1. prerequest: Executed before the HTTP request is sent.
    2. test: Executed after the HTTP request is sent and the response is received.

    Each event object requires a listen property (the event type) and a script object containing the type (usually text/javascript) and exec (the script code as an array of strings or a single string).

    {
        "id": "evented-item",
        "name": "Item with Events",
        "request": "http://echo.getpostman.com/get",
        "event": [
            {
                "listen": "prerequest",
                "script": {
                    "type": "text/javascript",
                    "exec": "console.log('We are in the pre-request script!')"
                }
            },
            {
                "listen": "test",
                "script": {
                    "type": "text/javascript",
                    "exec": "console.log('We are using the test script now!')"
                }
            }
        ]
    }
  4. Structure a Postman Collection

    develop

    A Collection is the root object. It must include an information block with a required schema property pointing to the valid Postman schema URL. The item array holds the contents of the collection, such as folders or requests.

    Required Schema URL: https://schema.getpostman.com/json/collection/v2.0.0/

    {
        "information": {
            "name": "My Collection",
            "version": "v2.0.0",
            "description": "This is a demo collection.",
            "schema": "https://schema.getpostman.com/json/collection/v2.0.0/"
        },
        "item": []
    }
  5. Define an Item and ItemGroup (Folder)

    develop

    An Item is the fundamental unit of a collection, representing an HTTP request. An ItemGroup (Folder) is a container used to organize Items into a hierarchy via an item array.

    Item Properties:

    • id: Unique identifier.
    • name: Display name.
    • request: Can be a simple URL string (defaults to GET) or a detailed JSON object.
    • response: An array of saved responses.
    • event: An array of lifecycle scripts.

    ItemGroup Properties:

    • item: An array containing nested Items or ItemGroups.
    {
        "id": "my-first-itemgroup",
        "name": "First Folder",
        "description": "This ItemGroup (Folder) contains two Items.",
        "item": [
            {
                "id": "1",
                "name": "Item A",
                "request": "http://echo.getpostman.com/get"
            },
            {
                "id": "2",
                "name": "Item B",
                "request": "http://echo.getpostman.com/headers"
            }
        ]
    }
  6. Get started with loading and exporting a collection

    develop

    To work with an existing Postman collection, you can load its JSON content from a file into a Collection instance using the postman-collection module. Once loaded, you can manipulate the collection and use .toJSON() to export it back to a JSON format compatible with Postman Apps and Newman.

    Note: You must use fs (or a similar file system module) to read the file from disk and JSON.parse() to convert the file content into a JavaScript object before passing it to the Collection constructor.

    var fs = require('fs'), // needed to read JSON file from disk
    	Collection = require('postman-collection').Collection,
    	myCollection;
    
    // Load a collection to memory from a JSON file on disk (say, sample-collection.json)
    myCollection = new Collection(JSON.parse(fs.readFileSync('sample-collection.json').toString()));
    
    // log items at root level of the collection
    console.log(myCollection.toJSON());
  7. How EventList handles event inheritance

    develop

    An EventList is a specialized PropertyList used to manage events within a Postman collection or item. It supports hierarchical inheritance: if an ItemGroup contains a set of events, its child Items will inherit those events from their parent.

    When retrieving listeners, EventList traverses up the parent chain to collect events, allowing you to define common tests or scripts at a high level (like a collection or folder) that automatically apply to all nested requests.

  8. Import the Postman Collection SDK

    develop

    The Postman Collection SDK provides a suite of classes to programmatically interact with, manipulate, and validate Postman collections. You can import the main entrypoint to access all core collection components such as Collection, Item, Request, Variable, and Header.

    const sdk = require('postman-collection');
    
    // Accessing core classes
    const Collection = sdk.Collection;
    const Item = sdk.Item;
    const Request = sdk.Request;
  9. Configure a Request object

    develop

    A Request defines the HTTP execution details. While an Item can use a simple string for a request, a full Request object allows for granular control over:

    • method: The HTTP verb (e.g., GET, POST).
    • url: The endpoint URL.
    • header: An array of key/value pairs.
    • body: The request payload (e.g., urlencoded, raw).
    • auth: Authentication configuration (e.g., basic, bearer).
    {
        "description": "This is a sample POST request",
        "url": "https://echo.getpostman.com/post",
        "method": "POST",
        "header": [
            {
                "key": "Content-Type",
                "value": "application/json"
            }
        ],
        "body": {
            "mode": "urlencoded",
            "urlencoded": [
                {
                    "key": "my-body-variable",
                    "value": "Something Awesome!"
                }
            ]
        }
    }
  10. Apply captured mutations to a different VariableScope

    develop

    Once mutations have been captured in a VariableScope, you can use the .applyOn() method on the mutations collection to replay those changes onto a different object. This is useful for mirroring the state of one scope onto another.

    var environmentCopy = new VariableScope();
    
    // applies the mutations captured on `environment` into `environmentCopy` making it a mirror
    environment.mutations.applyOn(environmentCopy);
  11. Enable mutation tracking in a VariableScope

    develop

    To track changes made to a VariableScope (such as an environment), you must explicitly call .enableTracking() on the instance. Once enabled, all subsequent set, unset, or clear operations are recorded in the mutations property of that scope.

    var VariableScope = require('postman-collection').VariableScope,
        environment = new VariableScope();
    
    // enables tracking mutations
    environment.enableTracking();