Using momentjs-timezone in Postman

External libraries can be executed in postman if CDN equivalent of these libraries are available.

You can get CDN in equivalent from websites like: https://cdnjs.com/

Now to use momentTZ in postman, copy the below code into script section and execute it once and then comment out:

This will store the CDN equivalent of momentTZ and momentJS libraries to environment variables.

pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.33/moment-timezone-with-data-2012-2022.min.js", (mtzErr, mtzRes) => {
pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js", (mjsErr, mjsRes) => {
//you have to initialize the momentjs to make momenttz work so we are storing both into a variable
pm.environment.set("momentjs", mjsRes.text());
pm.environment.set("momenttz", mtzRes.text());
})
})

Now you initiate the libraries in either of the two approaches:

First Approach:

Now comment out the above code you don’t need it anymore. Now you can use momenttz anywhere in your collection’s script sections as :

eval(pm.environment.get("momentjs"));
eval(pm.environment.get("momenttz"));
console.log(this.moment.utc().tz("America/Los_Angeles", "UTC").format())

in this approach, the libraries are initialized in the local scope, so if you want to use them again then you have to run the 3 lines of code again in other script sections whenever it’s used.

Second approach:

new Function triggers function in the global scope. so you just have to execute the first two lines only ones in your collection run and it will be available globally throughout:

Add in first scripts pre-request script:

(new Function(pm.environment.get("momentjs")))();
(new Function(pm.environment.get("momenttz")))();

Now you can use momentTZ library anywhere as :

console.log(moment.utc().tz("America/Los_Angeles", "UTC").format())

😀 😬 😁 😂 😃 😄 😅

Using external libraries in postman and there by using custom helper in Postman visualization!

Postman allows you to use CDN libraries in the script session,

so here we are using the CDN equivalent of the handlebar and then passing the compiled template to the postman visualizer

**We can initialize CDN in two ways :**

**First Approach:**

By initializing the CDN in global space using “new Function(cdn)()”

You can see the code below , but this will mess up global scope and can be used only once in the entire run*

// you can call any package with min build in postman
pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.js", (err, res) => {
pm.environment.set("res", res.text());
// intialize the min.js
new Function(pm.environment.get("res"))();
//create template soource
var source =
`{{#ifCond v1 v2}}
{{v1}} is equal to {{v2}}
{{else}}
{{v1}} is not equal to {{v2}}
{{/ifCond}}`;
//you can call methods in the cdn file using this keyword
//here we are registring handlebar
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
//compile the template
var template = Handlebars.compile(source);
//data to be passed 
// try v1 and v2 with same and different values and observe the output in visualization tab
var data = {
"v1": "test",
"v2": "test",
};
// passing the data to template
var result = template(data);
//visualizing it 
pm.visualizer.set(result)
})

**Second Approach:**

you can call any package with min build in postman

this initializes the functions in local scope so it won’t mess up the global space and cause issues

pm.sendRequest("https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js", (err, res) => {
pm.environment.set("res", res.text());
// intialize the min.js
eval(pm.environment.get("res"));
//create template soource
var source =
`{{#ifCond v1 v2}}
{{v1}} is equal to {{v2}}
{{else}}
{{v1}} is not equal to {{v2}}
{{/ifCond}}`;
//you can call methods in the cdn file using this keyword
//here we are registring handlebar
this.Handlebars.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
//compile the template
var template = this.Handlebars.compile(source);
//data to be passed
// try v1 and v2 with same and different values and observe the output in visualization tab
var data = {
"v1": "test",
"v2": "test",
};
// passing the data to template
var result = template(data);
//visualizing it
pm.visualizer.set(result)
})

The hidden gem: Postman API and Documentation feature

its easier than you would expect to create a project collection…

Postman API Feature:

you can create collection , mock servers, documentation in click of a button by using postman API definition feature.

Lets see how to do it!!

  1. Get the API definition:

postman supports following API definitions:

so what is API definitions ?

API definitions, or API specifications or description formats (all are the same) defines your API . It is like a live documentation on what is available, what it can do , what is supported etc . In short a comprehensive live documentation that can help consumers understand what your API can do.

in summary:

  • Help internal folks understand the API and agree on its attributes
  • Help external folks understand the API and what it can do
  • Act as live documentation on what all endpoints are available, what methods are supported, what attributes are expected etc.

https://swagger.io/blog/api-development/why-you-should-create-an-api-definition/

How to get API definition ?

Most APIs visualizes the API definition using swagger UI. Which creates a user interactable representation of your API from the API definition file.

In mostcases the swagger UI will have link to the definition file or you can goto network tab and search for it

lets take https://petstore.swagger.io/ as example.

you can see the link to the definition file, it can be in yaml or json format. just click the link and copy the content.

you can see the version is swagger 2.0 meaning its open api v2

2. Create API in Postman

click API section and click the add icon or create new API link

Now give the below details:

name,version , open api v2.0 and json , and click create

Now paste the swagger definition we copied from pet store:

you can press ctrl+b to format the json properly after pasting:

click save

3. Now Generate collection from this swagger definition:

click generate collection:

click show advanced settings:

Give the below settings:

Now click Generate collection and goto your collections once the collection generation completes

4. Mock server , documentation and other things

so the generated collection will have documentation and examples as per the API definition file provided so you don’t have to generate documentation separately!!

And for mockserver, you can directly create a mock server from the collection as the examples are already available.

5. Publishing your documentation and adding animation to your documentation

Click the collection and click view documentation , and click publish

Now you have the documentation available in public domain for your customers.

https://swagger.io/blog/api-development/why-you-should-create-an-api-definition/

To unpublish follow the same procedure and click edit documentation and click unpublish

Adding animation:

you can add gif to your documentation , to do that use :

copy the absolute url of your gif:

provide it in documentation as :

![](https://i.pinimg.com/originals/f0/6a/9b/f06a9b257ba15f4761308ff84ab1ba2b.gif)

so when you click outside it will be resolved as

How to run postman requests using Tags

Get all requests in the collection:

you can also get information about all the requests in a collection by using :

https://api.getpostman.com/collections/{{collection_UUID}}

to get uuid and api key goto :

https://app.getpostman.com

Now for generating api key >

goto account settings > api key and generate api key.

to get collection uuid goto specific workspace and collection and copy the uuid part from url:

Note: you can also get UUID by clicking collection and clicking info panel on the right side

Now in your collection

Rename all requests as:

get user details [Regression][Smoke][Somethingelse]
get account details [Regression]

Then Create a new request called initial request and keep it as the first request in your collection:

url: https://api.getpostman.com/collections/8xxxxtheuuidyoucopied

authorization: apikey-header : key: X-Api-Key and value: yourapikey

test-script :

pm.environment.unset("requestToRun")
reqeustlist = pm.response.json().collection.item.map((a) => a.name)
requestToRun = reqeustlist.filter((a) => a.includes(pm.environment.get("tag")))
let val = requestToRun.pop()
pm.environment.set("requestToRun", requestToRun)
val ? postman.setNextRequest(val) : postman.setNextRequest(null)

Now set the envirnoment variable as what you want to look for eg: run script that contains text “Regression” then set pm.environment.set("tag","Regression")

Now in your collection-pre-request add:

if (pm.info.requestName !== "initial request") {
let requestToRun = pm.environment.get("requestToRun")
let val = requestToRun.pop()
pm.environment.set("requestToRun", requestToRun)
val ? postman.setNextRequest(val) : postman.setNextRequest(null)
}

Output:

Ran only reqeusts that has “Copy” in its name

Example collection:

https://www.getpostman.com/collections/73e771fe61f7781f8598 , you can click ctrl+o and choose link to import this collection

Note: In newman you can pass the environment variable as “ — env-var tag=Regression”