### Accessing Descriptions Example Source: https://github.com/postmanlabs/postman-collection/wiki/Home Example demonstrating how to access and log descriptions of all root items in a collection. ```APIDOC ## Accessing Descriptions Example **Example** *(Accessing descriptions of all root items in a collection)* ```js 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.stringify(fs.readFileSync('sample-collection.json').toString())); // Log the description of all root items myCollection.item.all().forEach(function (item) { console.log(item.name || 'Untitled Item'); item.description && console.log(item.description.toString()); }); ``` ``` -------------------------------- ### Example URL Path with Query String Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example shows the expected output format for a complete URL path that includes a query string. ```plaintext /something/postman?hi=notbye ``` -------------------------------- ### Install Postman Collection SDK using NPM Source: https://github.com/postmanlabs/postman-collection/blob/develop/README.md Install the Postman Collection SDK and save it to your package.json using this NPM command. ```bash > npm install postman-collection --save ``` -------------------------------- ### Accessing Item Descriptions Source: https://github.com/postmanlabs/postman-collection/wiki/Home Example demonstrating how to access and log the descriptions of all root items within a Postman collection. ```APIDOC ## Accessing Item Descriptions ### Description This example shows how to load a Postman collection from a JSON file and then iterate through its root items to log their names and descriptions. ### Code Example ```js 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.stringify(fs.readFileSync('sample-collection.json').toString())); // Log the description of all root items myCollection.item.all().forEach(function (item) { console.log(item.name || 'Untitled Item'); item.description && console.log(item.description.toString()); }); ``` ``` -------------------------------- ### Create a Header Instance Source: https://github.com/postmanlabs/postman-collection/wiki/Home Use this snippet to create a new header instance by providing its definition as an object with 'key' and 'value' properties. The 'toString()' method can then be used to get its string representation. ```javascript var Header = require('postman-collection').Header, header = new Header({ key: 'Content-Type', value: 'application/xml' }); console.log(header.toString()) // prints the string representation of the Header. ``` -------------------------------- ### Manage Ordered Collections with PropertyList (HeaderList Example) Source: https://context7.com/postmanlabs/postman-collection/llms.txt PropertyList is a base class for managing ordered collections like HeaderList, CookieList, and VariableList. It provides methods for indexing, filtering, and traversal. This example demonstrates HeaderList usage. ```javascript const { Collection, Item, Header, HeaderList } = require('postman-collection'); // HeaderList usage (inherits PropertyList) const item = new Item({ name: 'Get Data', request: { url: 'https://api.example.com/data', method: 'GET', header: [ { key: 'Accept', value: 'application/json' }, { key: 'X-Request-ID', value: '123' } ] } }); const headers = item.request.headers; // Core PropertyList methods console.log(headers.count()); // 2 console.log(headers.has('Accept')); // true console.log(headers.one('Accept').value); // 'application/json' // Add / remove headers.add({ key: 'Cache-Control', value: 'no-cache' }); headers.remove(h => h.key === 'X-Request-ID'); console.log(headers.count()); // 2 // Iterate headers.each(h => console.log(`${h.key}: ${h.value}`)); // Accept: application/json // Cache-Control: no-cache // Filter and map const jsonHeaders = headers.filter(h => h.value.includes('json')); console.log(jsonHeaders.length); // 1 // Serialize to plain object (key → value) const obj = headers.toObject(false, false); console.log(obj); // { Accept: 'application/json', 'Cache-Control': 'no-cache' } // Serialize to array (toJSON) const arr = headers.toJSON(); console.log(arr[0]); // { key: 'Accept', value: 'application/json' } ``` -------------------------------- ### Request with Basic Authentication Source: https://github.com/postmanlabs/postman-collection/blob/develop/docs/concepts.md A simple GET request demonstrating the inclusion of basic authentication credentials. The SDK supports various authentication types. ```json { "url": "https://echo.getpostman.com/basic-auth", "method": "GET", "auth": { "type": "basic", "basic": { "username": "fred", "password": "hunter2" } } } ``` -------------------------------- ### ItemGroup Definition Example Source: https://github.com/postmanlabs/postman-collection/wiki/Home This is an example of the JSON structure that can be passed to create a new ItemGroup instance. It includes properties like name, id, item, auth, and event. ```json { "name": "Echo Get Requests", "id": "echo-get-requests", "item": [{ "request": "https://postman.com/get" }, { "request": "https://postman.com/headers" }], "auth": { "type": "basic", "basic": { "username": "jean", "password": "{{somethingsecret}}" } }, "event": [{ "listen": "prerequest", "script: { "type": "text/javascript", "exec": "console.log(new Date())" } }] } ``` -------------------------------- ### Add Item to Collection Example Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example demonstrates how to add a new Item to a folder within a Postman Collection instance. It requires importing the Collection and Item classes. ```javascript var Collection = require('postman-collection').Collection, Item = require('postman-collection').Item, myCollection; myCollection = new Collection({ "item": [{ "id": "my-folder-1", "name": "The solo folder in this collection", "item": [] // blank array indicates this is a folder }] }); // create a collection with an empty folder // add a request to "my-folder-1" that sends a GET request myCollection.items.one("my-folder-1").add(new Item({ "name": "Send a GET request", "id": "my-get-request" "request": { "url": 'https://postman.com/get", "method": "GET" } })); ``` -------------------------------- ### Adding Description to a Collection Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example shows how to create a new Postman collection and add a description to it using the `describe` method. The description can then be retrieved and logged. ```javascript var Collection = require('postman-collection').Collection, mycollection; // create a blank collection myCollection = new Collection(); myCollection.describe('Hey! This is a cool collection.'); console.log(myCollection.description.toString()); // read the description ``` -------------------------------- ### Add Description to a Collection Instance Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example shows how to create a new Postman Collection and add a plain text description to it using the `describe` method. The description can then be retrieved using `toString()`. ```javascript var Collection = require('postman-collection').Collection, mycollection; // create a blank collection myCollection = new Collection(); myCollection.describe('Hey! This is a cool collection.'); console.log(mycollection.description.toString()); // read the description ``` -------------------------------- ### Iterating on All Variables in a VariableScope Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example shows how to create a VariableScope with initial variables and then retrieve all variables as a plain object. It iterates over this object to log each variable's value. The variables can be of different types like string, number, or boolean. ```javascript var env = new VariableScope([{ key: 'var1', value: 'one' }, { key: 'var2', value: 2, type: 'number' }, { key: 'var3', value: true, type: 'boolean' }]), obj; // get all variables consolidated as an object obj = env.variables(); Object.keys(obj).forEach(function(varname) { console.log(obj[varname]); // log all variables }); ``` -------------------------------- ### Header Instance Methods Source: https://github.com/postmanlabs/postman-collection/wiki/Home Provides utility methods for interacting with Header instances, such as converting to a string, getting its value, updating properties, and traversing parent elements. ```APIDOC ## header.toString() ### Description Converts the header to a single header string ### Method instance method of `[Header](#Header)` ## header.valueOf() ### Description Return the value of this header ### Method instance method of `[Header](#Header)` ## header.update(options) ### Description Assigns the given properties to the Header ### Method instance method of `[Header](#Header)` ### Parameters #### Path Parameters - **options** (Object) - Required - Description of the options parameter ``` -------------------------------- ### Access Descriptions of Root Items in a Collection Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example shows how to load a Postman Collection from a JSON file and then iterate through its root items to log their names and descriptions. The 'fs' module is required to read the file. ```javascript 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.stringify(fs.readFileSync('sample-collection.json').toString())); // Log the description of all root items myCollection.item.all().forEach(function (item) { console.log(item.name || 'Untitled Item'); item.description && console.log(item.description.toString()); }); ``` -------------------------------- ### ProxyConfig Definition Example Source: https://github.com/postmanlabs/postman-collection/wiki/Home This JSON object structure is accepted as a constructor parameter for new ProxyConfig instances and is exported when toJSON or toObjectResolved is called on a Proxy instance. It defines the match URL, server, tunneling, and disabled status for proxy configurations. ```json { match: 'https://example.com/*', server: 'https://proxy.com', tunnel: true, disabled: false } ``` -------------------------------- ### variable.valueOf([value]) Source: https://github.com/postmanlabs/postman-collection/wiki/Home An alias for `get` and `set` methods, allowing to get or set the variable's value. ```APIDOC ## variable.valueOf([value]) ### Description An alias of this.get and this.set ### Method variable.valueOf([value]) ### Parameters #### Path Parameters - **[value]** (*): Optional. The value to set for the variable. If not provided, the current value is returned. ``` -------------------------------- ### Constructing an Event Source: https://github.com/postmanlabs/postman-collection/wiki/Home Demonstrates how to create a new Event instance by providing its definition, including the listen event and the script to be executed. ```javascript var Event = require('postman-collection').Event, rawEvent = { listen: 'test', script: 'tests["response code is 401"] = responseCode.code === 401' }, myEvent; myEvent = new Event(rawEvent); ``` -------------------------------- ### Create ProxyConfigList Instance Source: https://github.com/postmanlabs/postman-collection/wiki/Home Instantiate a new ProxyConfigList with initial proxy configurations. Accepts an object for options and an array of proxy objects. ```javascript var ProxyConfigList = require('postman-collection').ProxyConfigList, myProxyConfig = new ProxyConfigList({}, [ {match: 'https://example.com/*',server: 'https://proxy.com',tunnel: true}, {match: 'https://example2.com/*',server: 'http://proxy2.com'}, ]); ``` -------------------------------- ### Create and Assign Description to a Collection Source: https://github.com/postmanlabs/postman-collection/wiki/Home Demonstrates how to create a new Collection instance and assign a Description object to it, or use the `.describe` method for a simpler text description. ```javascript var SDK = require('postman-collection'), Collection = SDK.Collection, Description = SDK.Description, mycollection; // create a blank collection myCollection = new Collection(); mycollection.description = new Description({ content: '<h1>Hello World</h1><p>I am a Collection</p>', type: 'text/html' }); // alternatively, you could also use the `.describe` method of any property to set or update the description of the // property. mycollection.describe('Hey! This is a cool collection.'); ``` -------------------------------- ### Item Constructor Source: https://github.com/postmanlabs/postman-collection/wiki/Home Explains how to create a new Item instance, optionally providing an initial definition object that configures the request, responses, and scripts. ```APIDOC ## new Item([definition]) A Postman Collection Item that holds your request definition, responses and other stuff. An Item essentially is a HTTP request definition along with the sample responses and test scripts clubbed together. One or more of these items can be grouped together and placed in an [ItemGroup](#ItemGroup) and as such forms a [Collection](#Collection) of requests. | Param | Type | Description | | --- | --- | --- | | [definition] | `[definition](#Item..definition)` | While creating a new instance of Item, one can provide the initial configuration of the item with the the request it sends, the expected sample responses, tests, etc | **Example** *(Add a new Item to a folder in a collection instance)* ```js var Collection = require('postman-collection').Collection, Item = require('postman-collection').Item, myCollection; myCollection = new Collection({ "item": [{ "id": "my-folder-1", "name": "The solo folder in this collection", "item": [] // blank array indicates this is a folder }] }); // create a collection with an empty folder // add a request to "my-folder-1" that sends a GET request myCollection.items.one("my-folder-1").add(new Item({ "name": "Send a GET request", "id": "my-get-request" "request": { "url": 'https://postman-echo.com/get", "method": "GET" } })); ``` ``` -------------------------------- ### variable.get() Source: https://github.com/postmanlabs/postman-collection/wiki/Home Gets the current value of the variable. ```APIDOC ## variable.get() ### Description Gets the value of the variable ### Method variable.get() ### Returns - [types](#Variable.types): The value of the variable. ``` -------------------------------- ### ProxyConfigList Constructor Source: https://github.com/postmanlabs/postman-collection/wiki/Home Initializes a new ProxyConfigList with an optional array of proxy configurations. ```APIDOC ## new ProxyConfigList(populate) ### Description Creates a new instance of ProxyConfigList, optionally populating it with an array of proxy configuration objects. ### Method Constructor for ProxyConfigList ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **populate** (Array) - An array of proxy objects to initialize the list with. ### Request Example ```javascript var ProxyConfigList = require('postman-collection').ProxyConfigList, myProxyConfig = new ProxyConfigList({}, [ {match: 'https://example.com/*',server: 'https://proxy.com',tunnel: true}, {match: 'https://example2.com/*',server: 'http://proxy2.com'}, ]); ``` ### Response #### Success Response (200) - Returns a new ProxyConfigList instance. #### Response Example ```json { "example": "ProxyConfigList instance" } ``` ``` -------------------------------- ### proxyConfigList.idx(index) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Get a member of this list by its index. ```APIDOC ## proxyConfigList.idx(index) ### Description Get a member of this list by it's index. ### Parameters #### Path Parameters - **index** (Number) - The index of the member to retrieve. ### Returns - **PropertyList.Type** - The member at the specified index. ``` -------------------------------- ### Load, Modify, and Save Environment Variables Source: https://github.com/postmanlabs/postman-collection/wiki/Home Demonstrates how to load an environment from a file, perform calculations using its variables, and save the updated scope back to a file. Requires Node.js environment for file system operations. ```javascript var fs = require('fs'), // assuming NodeJS env, sum; // load env from file assuming it has initial data env = new VariableScope(JSON.parse(fs.readFileSync('./my-postman-environment.postman_environment').toString())); // get two variables and add them sum = env.get('one-var') + env.get('another-var'); // save it back in environment and write to file env.set('sum', sum, 'number'); fs.writeFIleSync('./sum-of-vars.postman_environment', JSON.stringify(env.toJSON())); ``` -------------------------------- ### Event.script Source: https://github.com/postmanlabs/postman-collection/wiki/Home Gets the script that is to be executed when this event is triggered. ```APIDOC ## event.script ### Description The script that is to be executed when this event is triggered. ### Method instance property ### Returns - **[Script](#Script)** - The associated script object. ``` -------------------------------- ### Header.create Source: https://github.com/postmanlabs/postman-collection/wiki/Home Creates a new header instance, optionally providing initial value and name. ```APIDOC ## Header.create([value], [name]) ### Description Create a new header instance. ### Parameters #### Path Parameters - **value** ([definition](#Header..definition) | String, Optional) - Pass the header definition as an object or the value of the header. If the value is passed as a string, it should either be in `name:value` format or the second "name" parameter should be used to pass the name as string. - **name** (String, Optional) - Optional override the header name or use when the first parameter is the header value as string. ``` -------------------------------- ### Event.listen Source: https://github.com/postmanlabs/postman-collection/wiki/Home Gets the name of the event that this instance is intended to listen to. ```APIDOC ## event.listen ### Description Name of the event that this instance is intended to listen to. ### Method instance property ### Returns - **String** - The name of the event. ``` -------------------------------- ### Request Constructor Source: https://github.com/postmanlabs/postman-collection/wiki/Home Initializes a new Request object with optional configuration options. ```APIDOC ## new Request(options) ### Description Constructs a new Postman HTTP request object. ### Parameters - **options** (`Object`): An object containing configuration options for the request. ``` -------------------------------- ### variable.valueType(typeName) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Sets or gets the type of the variable's value. ```APIDOC ## variable.valueType(typeName) ### Description Sets or gets the type of the value ### Method variable.valueType(typeName) ### Parameters #### Path Parameters - **typeName** (String): The name of the type to set or get. ### Returns - String: Returns the current type of the variable from the list of [types](#Variable.types). ``` -------------------------------- ### Collection - Create, Load, and Export a Collection Source: https://context7.com/postmanlabs/postman-collection/llms.txt Demonstrates how to create a new Postman Collection from scratch, add folders and requests, export it to a JSON file, and then load an existing collection from a file. It also shows how to sync variables. ```APIDOC ## Collection - Create, Load, and Export a Collection `Collection` is the root class representing an entire Postman Collection. It extends `ItemGroup` and adds a `variables` list and an optional semver `version`. Pass a plain JS object matching the collection format to the constructor, or build up a new collection from scratch and call `toJSON()` to serialize. ### Usage Example ```javascript const fs = require('fs'); const { Collection, Item, ItemGroup, Request, Variable } = require('postman-collection'); // --- Build a new collection from scratch --- const col = new Collection({ info: { name: 'My API', version: '1.0.0' }, variable: [{ key: 'baseUrl', value: 'https://api.example.com', type: 'string' }] }); // Add a folder const folder = new ItemGroup({ name: 'Users' }); // Add a request item to the folder folder.items.add(new Item({ name: 'List Users', request: { url: '{{baseUrl}}/users', method: 'GET', header: [{ key: 'Accept', value: 'application/json' }] } })); col.items.add(folder); // Export to file fs.writeFileSync('my-api.postman_collection.json', JSON.stringify(col.toJSON(), null, 2)); console.log('Collection exported.'); // --- Load an existing collection from file --- const loaded = new Collection(JSON.parse(fs.readFileSync('my-api.postman_collection.json', 'utf8'))); console.log('Loaded collection name:', loaded.name); // 'My API' console.log('Is collection?', Collection.isCollection(loaded)); // true // Sync variables to/from a plain object col.syncVariablesFrom({ baseUrl: 'https://staging.example.com' }); console.log(col.variables.get('baseUrl').valueOf()); // 'https://staging.example.com' ``` ``` -------------------------------- ### queryParam.findInParents(property) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Searches for a specific property starting from the current QueryParam element and moving up the parent chain. ```APIDOC ## queryParam.findInParents(property) ### Description Tries to find the given property locally, and then proceeds to lookup in each parent, going up the chain as necessary. ### Kind instance method of `[QueryParam](#QueryParam)` ### Parameters #### Path Parameters - **property** (String) - Required - The property to search for. ``` -------------------------------- ### Create, Load, and Export a Postman Collection Source: https://context7.com/postmanlabs/postman-collection/llms.txt Demonstrates building a new collection from scratch, adding folders and requests, exporting it to a JSON file, and then loading it back. Also shows how to sync variables. ```javascript const fs = require('fs'); const { Collection, Item, ItemGroup, Request, Variable } = require('postman-collection'); // --- Build a new collection from scratch --- const col = new Collection({ info: { name: 'My API', version: '1.0.0' }, variable: [{ key: 'baseUrl', value: 'https://api.example.com', type: 'string' }] }); // Add a folder const folder = new ItemGroup({ name: 'Users' }); // Add a request item to the folder folder.items.add(new Item({ name: 'List Users', request: { url: '{{baseUrl}}/users', method: 'GET', header: [{ key: 'Accept', value: 'application/json' }] } })); col.items.add(folder); // Export to file fs.writeFileSync('my-api.postman_collection.json', JSON.stringify(col.toJSON(), null, 2)); console.log('Collection exported.'); // --- Load an existing collection from file --- const loaded = new Collection(JSON.parse(fs.readFileSync('my-api.postman_collection.json', 'utf8'))); console.log('Loaded collection name:', loaded.name); // 'My API' console.log('Is collection?', Collection.isCollection(loaded)); // true // Sync variables to/from a plain object col.syncVariablesFrom({ baseUrl: 'https://staging.example.com' }); console.log(col.variables.get('baseUrl').valueOf()); // 'https://staging.example.com' ``` -------------------------------- ### new VariableList(populate, environment, global) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Initializes a new VariableList. This class extends PropertyList and is used for managing variables within different scopes. ```APIDOC ## new VariableList(populate, environment, global) ### Description Initializes a new VariableList. This class extends `[PropertyList](#PropertyList)` and is used for managing variables within different scopes. ### Parameters #### Path Parameters - **populate** (Object) - Required - An object to populate the variable list with. - **environment** (Object) - Required - The environment object. - **global** (Object) - Required - The global object. ``` -------------------------------- ### proxyConfigList.one(id) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Get an Item in this list by its `ID` reference. If multiple values are allowed, the last value is returned. ```APIDOC ## proxyConfigList.one(id) ### Description Get Item in this list by `ID` reference. If multiple values are allowed, the last value is returned. ### Parameters #### Path Parameters - **id** (String) - Description not available ### Returns - **PropertyList.Type** - The found item or last matching item. ``` -------------------------------- ### JSON Definition of a VariableScope Source: https://github.com/postmanlabs/postman-collection/wiki/Home This is an example of the data structure used for defining environments and globals in Postman. It can be passed to the constructor of `VariableScope` or `VariableList`. ```json { "name": "globals", "values": [{ "key": "var-1", "value": "value-1" }, { "key": "var-2", "value": "value-2" }] } ``` -------------------------------- ### url.toJSON() Source: https://github.com/postmanlabs/postman-collection/wiki/Home Returns the JSON representation of a property, which conforms to the way it is defined in a collection. This method can be used to get the instantaneous representation of any property. ```APIDOC ## url.toJSON() ### Description Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a [Collection](#Collection). ### Method instance method of `[Url](#Url)` ``` -------------------------------- ### proxyConfigList.get(key) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Get the value of an item in this list. This is similar to `PropertyList.one` but returns the value of the underlying type of the list content instead of the item itself. ```APIDOC ## proxyConfigList.get(key) ### Description Get the value of an item in this list. This is similar to [PropertyList.one](PropertyList.one) barring the fact that it returns the value of the underlying type of the list content instead of the item itself. ### Parameters #### Path Parameters - **key** (String | function) - Description not available ### Returns - **PropertyList.Type** - The value of the item. ``` -------------------------------- ### proxyConfigList.populate(items) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Load one or more items into the list. ```APIDOC ## proxyConfigList.populate(items) ### Description Load one or more items. ### Parameters #### Path Parameters - **items** (Object | Array) - Description not available ``` -------------------------------- ### Load and Log a Postman Collection from a File Source: https://github.com/postmanlabs/postman-collection/blob/develop/README.md Load a Postman Collection from a JSON file into memory and log its JSON representation to the console. Ensure the 'sample-collection.json' file exists in the same directory or provide the correct path. ```javascript 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()); ``` -------------------------------- ### Item Definition Example Source: https://github.com/postmanlabs/postman-collection/wiki/Home This JSON object represents a complete definition for a Postman Collection Item, including its name, ID, description, and request details. ```js { "name": "Get Headers from Echo", "id": "my-request-1", "description": "Makes a GET call to echo service and returns the client headers that were sent", "request": { "url": "https://postman-echo.com/headers", "method": "GET" } } ``` -------------------------------- ### ProxyConfig Instance Methods Source: https://github.com/postmanlabs/postman-collection/wiki/Home Instance methods available for the ProxyConfig class. ```APIDOC ## proxyConfig.update(options) ### Description Updates the proxy configuration with the provided options. ### Method instance method of ProxyConfig ### Parameters #### Path Parameters - **options** (Object) - Description not available ``` ```APIDOC ## proxyConfig.test([urlStr]) ### Description Tests if the proxy configuration matches the given URL string. ### Method instance method of ProxyConfig ### Parameters #### Path Parameters - **urlStr** (String) - Optional - The URL string to test against. ### Returns - **Boolean** - Description not available ``` -------------------------------- ### ItemGroup (Folder) Structure Source: https://github.com/postmanlabs/postman-collection/blob/develop/docs/concepts.md An ItemGroup, also known as a Folder, used to organize multiple Items within a collection. This example contains two Items. ```json { "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" } ] } ``` -------------------------------- ### Create Blank Collection and Write to File Source: https://github.com/postmanlabs/postman-collection/wiki/Home Illustrates how to create a new, empty Postman Collection with a specified name and then write its string representation to a file. Uses the 'fs' module for file writing. ```javascript var fs = require('fs'), Collection = require('postman-collection').Collection, mycollection; myCollection = new Collection({ info: { name: "my Collection" } }); // log the collection to console to see its contents fs.writeFileSync('myCollection.postman_collection', myCollection.toString()); ``` -------------------------------- ### Script.prototype.toJSON Source: https://github.com/postmanlabs/postman-collection/wiki/Home Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a Collection. ```APIDOC ## script.toJSON() ### Description Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a [Collection](#Collection). ### Returns - (Object) - The JSON representation of the property. ``` -------------------------------- ### response.toJSON Source: https://github.com/postmanlabs/postman-collection/wiki/Home Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a Collection. ```APIDOC ## response.toJSON() ### Description Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a [Collection](#Collection). ### Returns - (Object) - The JSON representation of the property. ``` -------------------------------- ### proxyConfigList.all() Source: https://github.com/postmanlabs/postman-collection/wiki/Home Returns a map of all items in the list. ```APIDOC ## proxyConfigList.all() ### Description Returns a map of all items. ### Returns - **Object** - A map of all items. ``` -------------------------------- ### requestAuthBase.toJSON Source: https://github.com/postmanlabs/postman-collection/wiki/Home Returns the JSON representation of a property, which conforms to the way it is defined in a collection. This method can be used to get the instantaneous representation of any property, including a Collection. ```APIDOC ## requestAuthBase.toJSON() Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a [Collection](#Collection). **Kind**: instance method of `[RequestAuthBase](#RequestAuthBase)` ``` -------------------------------- ### proxyConfigList.each() Source: https://github.com/postmanlabs/postman-collection/wiki/Home Iterate on each item of this list. ```APIDOC ## proxyConfigList.each() ### Description Iterate on each item of this list. ``` -------------------------------- ### property.toJSON() Source: https://github.com/postmanlabs/postman-collection/wiki/Home Returns the JSON representation of a property, which conforms to the way it is defined in a collection. This method can be used to get the instantaneous representation of any property, including a Collection. ```APIDOC ## property.toJSON() ### Description Returns the JSON representation of a property, which conforms to the way it is defined in a collection. You can use this method to get the instantaneous representation of any property, including a [Collection](#Collection). **Kind**: instance method of `[Property](#Property)` ``` -------------------------------- ### Create and Manage an HTTP Request Item Source: https://context7.com/postmanlabs/postman-collection/llms.txt Shows how to create a new Item with a full request definition, including headers, body, events, and responses. It also covers retrieving and inspecting the item, and setting authorization. ```javascript const { Collection, Item, Request, Response } = require('postman-collection'); const col = new Collection({ info: { name: 'Demo' } }); // Create an item with a full request definition const item = new Item({ name: 'Create User', id: 'create-user', request: { url: 'https://api.example.com/users', method: 'POST', header: [{ key: 'Content-Type', value: 'application/json' }], body: { mode: 'raw', raw: JSON.stringify({ name: 'Alice', role: 'admin' }) } }, event: [{ listen: 'test', script: { type: 'text/javascript', exec: 'pm.test("Status is 201", () => pm.response.to.have.status(201));' } }], response: [{ name: 'Success', code: 201, status: 'Created', header: [{ key: 'Content-Type', value: 'application/json' }], body: '{"id":"123","name":"Alice"}' }] }); col.items.add(item); // Retrieve and inspect const found = col.items.one('create-user'); console.log(found.name); // 'Create User' console.log(found.request.method); // 'POST' console.log(found.getEvents('test').length); // 1 // Navigate the item path (collection name → item name) console.log(found.getPath()); // ['Demo', 'Create User'] // Set auth on the item's request found.authorizeRequestUsing('bearer', [{ key: 'token', value: 'mytoken123' }]); console.log(found.request.auth.type); // 'bearer' ``` -------------------------------- ### Define Basic Auth for a Collection Source: https://github.com/postmanlabs/postman-collection/wiki/Home This snippet demonstrates how to add basic authentication to an entire Postman Collection, which will then be applied to all requests within it. Ensure you have the 'postman-collection' library installed. ```javascript var fs = require('fs'), Collection = require('postman-collection').Collection, RequestAuth = require('postman-collection').RequestAuth, mycollection; // Create a collection having two requests myCollection = new Collection(); myCollection.items.add([ { name: 'GET Request', request: 'https://postman-echo.com/get?auth=basic' }, { name: 'PUT Request', request: 'https://postman-echo.com/put?auth=basic' } ]); // Add basic auth to the Collection, to be applied on all requests. myCollection.auth = new RequestAuth({ type: 'basic', username: 'postman', password: 'password' }); ``` -------------------------------- ### ProxyConfigList Methods Source: https://github.com/postmanlabs/postman-collection/wiki/Home Methods available for interacting with a list of proxy configurations. ```APIDOC ## proxyConfigList.indexOf(item) ### Description Find the index of an item in this list. ### Method instance method of ProxyConfigList ### Parameters #### Path Parameters - **item** (String | Object) - Description not available ``` ```APIDOC ## proxyConfigList.has(item) ### Description Check whether an item exists in this list. ### Method instance method of ProxyConfigList ### Parameters #### Path Parameters - **item** (String | PropertyList.Type) - Description not available ``` ```APIDOC ## proxyConfigList.eachParent(iterator, [context]) ### Description Iterates over all parents of the property list. ### Method instance method of ProxyConfigList ### Parameters #### Path Parameters - **iterator** (function) - Description not available - **context** (Object) - Optional - Description not available ``` ```APIDOC ## proxyConfigList.toObject() ### Description Converts a list of Properties into an object where key is `_postman_propertyIndexKey` and value is determined by the `valueOf` function. ### Method instance method of ProxyConfigList ### Returns - **Object** - Description not available ``` ```APIDOC ## proxyConfigList.toString() ### Description Adds ability to convert a list to a string provided its underlying format has unparse function defined. ### Method instance method of ProxyConfigList ### Returns - **String** - Description not available ``` -------------------------------- ### script.exec Source: https://github.com/postmanlabs/postman-collection/wiki/Home Kind: instance property of Script. Extends: Script.prototype. ```APIDOC ## script.exec : Array ### Description Kind: instance property of Script. Extends: Script.prototype. ### Type - Array ``` -------------------------------- ### Example Postman Collection Definition Source: https://github.com/postmanlabs/postman-collection/wiki/Home This JSON object represents a basic Postman collection, including its info, items, and variables. It's useful for understanding the structure required for creating or importing collections. ```js { "info": { "name": "My Postman Collection", "version": "1.0.0" } "item": [{ "request": "{{base-url}}/get" }], "variables": [{ "id": "base-url", "value": "https://postman-echo.com" }] } ``` -------------------------------- ### Script.prototype.describe Source: https://github.com/postmanlabs/postman-collection/wiki/Home Describes the script with given content and type. ```APIDOC ## script.describe(content, [type]) ### Description Describes the script with given content and type. ### Parameters #### Path Parameters - **content** (*) - Required - The content to describe the script with. - **type** (*) - Optional - The type of the description. ``` -------------------------------- ### Create New ItemGroup in Collection Source: https://github.com/postmanlabs/postman-collection/wiki/Home Demonstrates how to add a new, empty ItemGroup (folder) to an existing Collection instance. ```javascript var Collection = require('postman-collection').Collection, ItemGroup = require('postman-collection').ItemGroup, myCollection; myCollection = new Collection(); // create an empty collection myCollection.add(new ItemGroup({ "name": "This is a blank folder" })); ``` -------------------------------- ### PropertyList - Generic Typed List Source: https://context7.com/postmanlabs/postman-collection/llms.txt PropertyList is a base class for managing ordered collections of typed members, providing APIs for indexing, filtering, and traversal. Examples include HeaderList, CookieList, VariableList, and EventList. ```APIDOC ## PropertyList ### Description `PropertyList` is the base class for `HeaderList`, `CookieList`, `VariableList`, `EventList`, etc. It provides a rich API for managing ordered collections of typed members with indexing, filtering, and traversal. ### Usage Example (HeaderList) ```js const { Collection, Item, Header, HeaderList } = require('postman-collection'); // HeaderList usage (inherits PropertyList) const item = new Item({ name: 'Get Data', request: { url: 'https://api.example.com/data', method: 'GET', header: [ { key: 'Accept', value: 'application/json' }, { key: 'X-Request-ID', value: '123' } ] } }); const headers = item.request.headers; // Core PropertyList methods console.log(headers.count()); // 2 console.log(headers.has('Accept')); // true console.log(headers.one('Accept').value); // 'application/json' // Add / remove headers.add({ key: 'Cache-Control', value: 'no-cache' }); headers.remove(h => h.key === 'X-Request-ID'); console.log(headers.count()); // 2 // Iterate headers.each(h => console.log(`${h.key}: ${h.value}`)); // Accept: application/json // Cache-Control: no-cache // Filter and map const jsonHeaders = headers.filter(h => h.value.includes('json')); console.log(jsonHeaders.length); // 1 // Serialize to plain object (key → value) const obj = headers.toObject(false, false); console.log(obj); // { Accept: 'application/json', 'Cache-Control': 'no-cache' } // Serialize to array (toJSON) const arr = headers.toJSON(); console.log(arr[0]); // { key: 'Accept', value: 'application/json' } ``` ``` -------------------------------- ### proxyConfigList.prepend(item) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Adds or moves an item to the beginning of this list. ```APIDOC ## proxyConfigList.prepend(item) ### Description Adds or moves an item to the beginning of this list. ### Parameters #### Path Parameters - **item** (PropertyList.Type) - Description not available ``` -------------------------------- ### proxyConfig.description Source: https://github.com/postmanlabs/postman-collection/wiki/Home Holds detailed documentation for the property, which can be in plain text, HTML, or Markdown format. It is recommended to use the `describe` function to update this property. ```APIDOC ## proxyConfig.description : Description The `description` property holds the detailed documentation of any property. The description can be written in plain text, html or markdown as mentioned in [format](#Description.format) enumeration. It is recommended that this property be updated using the [describe](#describe) function. **Kind**: instance property of `[ProxyConfig](#ProxyConfig)` **See**: Property#describe **Example** *(Accessing descriptions of all root items in a collection)* ```js 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.stringify(fs.readFileSync('sample-collection.json').toString())); // Log the description of all root items myCollection.item.all().forEach(function (item) { console.log(item.name || 'Untitled Item'); item.description && console.log(item.description.toString()); }); ``` ``` -------------------------------- ### Get Item Events by Name in JavaScript Source: https://github.com/postmanlabs/postman-collection/wiki/Home Retrieves all events associated with a specific event name (e.g., 'test', 'prerequest') from a Postman Item. If no name is provided, it returns all events. This is useful for executing associated scripts. ```javascript 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.stringify(fs.readFileSync('sample-collection.json').toString())); // assuming the collection has a request called "my-request-1" in root, we get it's test events myCollection.items.one("my-request-1").getEvents("test").forEach(function (event) { event.script && eval(event.script.toSource()); }); ``` -------------------------------- ### eventList.prepend(item) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Adds or moves an item to the beginning of the list. ```APIDOC ## eventList.prepend(item) ### Description Adds or moves an item to the beginning of this list. ### Parameters #### Path Parameters - **item** (PropertyList.Type) - The item to add to the beginning of the list. ``` -------------------------------- ### Parsing Response Body as JSON Source: https://github.com/postmanlabs/postman-collection/wiki/Home This example shows how to safely parse a response body as a JSON object. It includes error handling for invalid JSON and an option for strict parsing, which rejects comments and BOM. The 'reviver' function can be used for custom parsing logic. ```javascript // assuming that the response is stored in a collection instance `myCollection` var response = myCollection.items.one('some request').responses.idx(0), jsonBody; try { jsonBody = response.json(); } catch (e) { console.log("There was an error parsing JSON ", e); } // log the root-level keys in the response JSON. console.log('All keys in json response: ' + Object.keys(json)); ``` -------------------------------- ### Create and Parse HTTP Response Objects Source: https://context7.com/postmanlabs/postman-collection/llms.txt Illustrates creating a Response object, accessing its properties, parsing JSON bodies, and extracting content information. Use this to represent and work with HTTP responses programmatically. ```javascript const { Response, Request } = require('postman-collection'); const res = new Response({ code: 200, status: 'OK', header: [ { key: 'Content-Type', value: 'application/json; charset=utf-8' }, { key: 'Content-Length', value: '42' } ], body: '{"id":1,"name":"Alice","active":true}', responseTime: 123, originalRequest: { url: 'https://api.example.com/users/1', method: 'GET' } }); // Access basic properties console.log(res.code); // 200 console.log(res.reason()); // 'OK' console.log(res.status); // 'OK' // Parse JSON body try { const data = res.json(); console.log(data.name); // 'Alice' } catch (e) { console.error('Invalid JSON:', e.message); } // Content info (mime type, charset, etc.) const info = res.contentInfo(); console.log(info.contentType); // 'application/json' console.log(info.charset); // 'utf-8' // Size breakdown const size = res.size(); console.log(`Body: ${size.body}B, Header: ${size.header}B, Total: ${size.total}B`); // Convert to data URI (for binary responses) const dataUri = res.dataURI(); console.log(dataUri.startsWith('data:application/json')); // true // Build from a Node.js http response object const nodeResponse = { body: Buffer.from('{"ok":true}'), headers: {}, statusCode: 200, statusMessage: 'OK', elapsedTime: 50 }; const sdkRes = Response.createFromNode(nodeResponse, []); console.log(sdkRes.text()); // '{"ok":true}' ``` -------------------------------- ### proxyConfig.describe(content, [type]) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Allows describing a property for documentation purposes by setting or updating its `description` child-property. The content can be plain text, Markdown, or HTML. ```APIDOC ## proxyConfig.describe(content, [type]) This function allows to describe the property for the purpose of detailed identification or documentation generation. This function sets or updates the `description` child-property of this property. **Kind**: instance method of `[ProxyConfig](#ProxyConfig)` | Param | Type | Default | Description | | --- | --- | --- | --- | | content | `String` | | The content of the description can be provided here as a string. Note that it is expected that if the content is formatted in any other way than simple text, it should be specified in the subsequent `type` parameter. | | [type] | `String` | `"text/plain"` | The type of the content can be one of the values mentioned in [format](#Description.format) enumeration - namely `text/plain`, `text/markdown` or `text/html`. | **Example** *(Add a description to an instance of Collection)* ```js var Collection = require('postman-collection').Collection, mycollection; // create a blank collection mycollection = new Collection(); mycollection.describe('Hey! This is a cool collection.'); console.log(mycollection.description.toString()); // read the description ``` ``` -------------------------------- ### propertyList.populate(items) Source: https://github.com/postmanlabs/postman-collection/wiki/Home Loads one or more items into the PropertyList. ```APIDOC ## propertyList.populate(items) ### Description Load one or more items. ### Parameters #### Path Parameters - **items** (Object | Array) - Required - The items to load. ### Method instance method of [PropertyList](#PropertyList) ```