Automating the saving of cookies from requests made in Postman

Jairo Andres Ruiz Machado

Solutions Specialist

 

 

Many times when dealing with APIs or microservices we need to save cookies that they send us in response to certain requests, such as authentication or session cookies to validate subsequent requests. This can lead to a tedious process of manually copying the cookies each time a request is sent, and even more tedious if you have to replace these same values if you are testing with multiple instances or users.

With Postman, it is possible to automate this process in several ways. Postman offers a browser extension where it is able to intercept requests made from the browser and capture the cookies that are delivered back. This is a good solution, but has the limitation that the request must be made through a Chrome-based browser. Postman also offers the ability to modify cookies programmatically, using JavaScript scripting to access request and response values. For the response case, this can be found under the Tests tab in the graphical interface.

This is where we can generate code that will run after the request has been sent and a response has been received. Postman's JavaScript reference indicates that the response cookies are located under pm.response.cookies.jar where the ''jar'' object is a collection of cookies belonging to the specific domain where the request was sent. Postman maintains its own collection of cookies as an object under pm.cookies.jar. It turns out that to this global collection collections can be added by simply assigning the collection returned by a request. The code to do this is simple:

The result of this script when run is as follows:

We start with an empty collection.

We send the request, the script runs automatically after receiving the response.

The collection specific to that domain is now inside the Postman cookie collection.

The script not only adds cookies and is able to replace the values if they belong to the same domain, but also adds collections of different domains that do not exist in the cookie jar without having to add additional logic.

 

This therefore helps streamline a workflow where cookies from one or more domains need to be saved for testing, QA or other purposes.