Postman – The Bearer of good news…

For a long time, I was doing something that just felt a bit wrong but it worked so I went with it, until I found an awesome community member, that decided to share their work to a wider audience. I can’t stress enough how important it is to do that, you may feel that what you’re doing is not going to be of any use to people but I can assure you….It really is!!

For a while, I was getting an Authentication Bearer token for my API requests…kinda manually, I wasn’t physically copying and pasting but I might as well of done this each time. I was already making use of the Pre-request Scripts and the environment variables but my Auth request, that I set up, was happening before every request, instead of checking to see if the token was actually still valid first – In hindsight, the way I had it was awful but because it wasn’t adding any real noticeable latency, I just kept my collections as they were, I knew that I was sending unnecessary requests each time but I was semi-fine with that happening.

I mentioned before about the importance of sharing what you do, Ben Chartrand did just that in this blog post, this was exactly what I was looking for and it was simple enough to understand straight away – again, that’s always good when you’re sharing your knowledge.

It seems pretty pointless, basically sharing Ben’s work again in another post but as I have been recently using the built-in modules like Moment and Lodash within Postman, I changed the script slightly to use these modules and refactor the code while doing so. It’s only a small difference and all the credit should absolutely go to Ben for getting the original script together in the first place.

So what have I done differently…

getToken
Collection ‘Pre-Request Script’

 

The main change has been around the first ‘If‘ statement – In Postman, you can return all the environment variables, in a JavaScript object, by using the ‘pm.environment.toObject()‘ function . Using the Lodash _.has function, I’m looking within that object to see if it contains the ‘AccessTokenExpiry‘ or ‘jwt‘ properties, If it doesn’t… It’ll go and get a new token.

As well as this check, I’m also checking to see that the ‘AccessTokenExpiry‘ value (in milliseconds) is still valid. This is checking against the current date and time. This date is returned in milliseconds using the ‘moment().valueOf()‘ function. Love this site as a quick reference to convert milliseconds into a human readable date and time.

The only other difference is in the ‘pm.sendRequest()‘ function where I’m using momentjs once again, to set the ‘expiryDate‘ value by taking the current time in milliseconds and then adding the ‘expires_in‘ response value to this time. This will then give us a time in the future that the token will expiry. If we send a new request and the token has expired – we will hit one of the first ‘If‘ statement conditions and it will go and get another valid token. Simple.

I have different files created for each of my environments so it’s just a case of switching between these files, If I want to run requests locally, in Staging or on Production.

My environment files would hold the ‘AuthData‘ and the ‘tokenBaseURL‘ variable values that are referenced in the Pre-request Script.

Test_Environment_File
Test Environment File

The ‘AuthData’ value is the ‘client_id’ and ‘client_secret’ values that have been base64 encoded – This can be encoded using any of the online tools out there such as https://www.base64encode.org/ or you could just modify the token script slightly to add those raw values straight into the request or as separate values in the environment files. Your context and personal preference will help you choose with method you use.

Modified_Script
Auth details added to the token script

That’s it, like I mentioned before, the majority of the work has been done by Ben. By him sharing the original information with a wider audience, It has helped me and many others use the Postman application in a more efficient way and I can only say huge thank you for that.

I’ve added the code here so you can have a closer look at what’s going on in your own local instances:

Advertisements

Postman and Lodash – The perfect partnership

In a previous post I wrote about using momentjs within Postman, this is an excellent utility module that makes working with times and dates in JavaScript so much easier.

I wanted to continue my love for these utility modules by introducing another one that can be used within the application. This time it’s Lodash, this just makes working with arrays, objects, numbers, strings etc. So much easier by providing a library of amazing methods that take some of the pain away from using native JavaScript.

I’m not going to go too in-depth with explaining the whole module because it’s epic and this post could go on forever but I wanted to give you some basic examples, using a few of the functions, for certain use cases within Postman. My aim is to get you interested in using Lodash and give you a starting point from which to explore some of the other functions that the library has to offer.

Accessing the Lodash module within the application

There is for some reason (I have no idea why…) two different ways to get access to Lodash, for all the version 4.17.4 functions you will need to add a `require(‘lodash’)` statement at the start of your scripts.

The way that I would use it is slightly different though, most of the features that I have ever used are contained in version 3.10.1 and to use these you don’t need to ‘require’ the module, you just simply jump straight in and use the `_` variable in your scripts.

So that’s how to get access to the module but how do we use it and why is it better easier than using native JavaScript?

Some very basic usage examples

The `Pre-request Script` and `Tests` tabs are basically little JavaScript IDE’s and they give us the ability to write small scripts, to assist us with things like creating test data or managing the response data that we receive from an API endpoint.

In my limited experience, a whole group of questions that I’ve answered on Stackoverflow have been related to checking specific parts of a JSON response – This is where I feel Lodash makes life easier, the native JS syntax for looping through data looks awful and if you’re not too familiar with the language, it’s easy to get it wrong and be left confused.

Using the native JavaScript `for` loop just looks ugly and I’ve lost count of the number of times that I have googled the correct syntax to use! 😦 This first example is using the built-in `pm.response.json()` function which parses the JSON response body data.

This is the native JS `for` loop that would iterate through the data and build up an index of the items using the .length method to know when it’s done.

Native_loop
Native JS ‘for’ loop

 

This is the Lodash for loop using the .each() function, using `forEach()` is the same thing but I’m using its alias instead. This would iterate through the same data and hold all the data in the item index, ready to be used.

Lodash_loop
Lodash ‘for’ loop

 

Let’s take a look at this in action with Postman. I’m using the loop with the pm.test() function, to check that the gender property of each object in the array, is either Male or Female. The pm.expect() is using the Chaijs syntax.

Lodash_Loop_Usage
Using the _.each() loop in Postman

 

Another example of where the Lodash functions can help us out, is when we need to create some dynamic data to use in our requests. In the Pre-request Script tab, we can create all of this data before the main request is sent.

There are a couple of handy dynamic variables in Postman like ‘{{$randomInt}}‘ that help with placing a random number into a request but these are quite limited in terms of the number range. Lodash has the ‘_.random()‘ function that extends this slightly and will give a bit more control over the range of numbers returned.

 

Random_Numbers
The ‘_.random()’ Lodash function syntax

 

Using these in Postman is very simple, all we need to do is use either the environment or globals postman set function, to set the variable value. This can then be used in our requests with the `{{var_name}}` syntax.

Lodash_Random_Numbers
Using the ‘_.random()’ function in Postman

 

Very briefly we have seen how useful Lodash can be when creating data for our requests or easily iterating through some response data, to help assert that a certain value is present. Postman is great for just debugging responses too, not every request you build needs to have a Test or used as part of an automated check suite.

I love using the Postman Console, this allows me to inspect different parts of the request or the response, to narrow down problems that I may be having. Pretty much every thing that you do in Postman can be logged out to the console using a simple `console.log()` statement in either the Pre-request Scripts or Tests tab.

I’m going to look at possible (totally made up…) use case where we can use the _.chain() function to group multiple Lodash functions, in order to filter down the response data, to log out a specific area that is causing us a problem. The sample JSON data below is just a group of users that are returned over our mock API endpoint.

Sample_Response
Sample JSON response data

 

The _.chain() function allows us to use lots of different functions, at the same time, to change and manipulate the response data. This can help us focus in on the parts of the data that are important to us, when looking at our problem.

There is a kinda book-end feel to this function, we start it with the _.chain() function and close it out with the .value() function. The part in the middle is doing the leg work and each one is changing the data, as it passes through, leaving us with the value(s) that we want to display.

Basically, I’m using the .map() function to get all the values from the ‘favourite_colour‘ property and placing those into separate arrays, then I’m using the .flatten() function to flatten the arrays into a single array. Finally, I’m using the _.uniq() function to filter the flattened array, to only return unique ‘favourite_colour’ values.

Lodash_Filter
Lodash ‘_.chain()’ function

 

There is a lot going on there but hopefully it’s short enough to follow the data path. This is the console output of the filtered down response data, showing us all the unique ‘favourite colours’, from all of our users.

Lodash_Chain_Example
Using the _.chain() function in Postman

 

So that was a very quick and basic look and using Lodash and it’s many wonderful functions within the Postman application. The module is huge and I would totally recommend exploring it to find the functions that could be useful in your context.

Here are some additional Lodash resources that might be useful to you, they all contain examples of ways that some of the functions can be used: