Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a Postman header value into a variable throughout requests in a collection

I am trying to automate my test suite in Postman so that I don't have to manually go into each request and change that header value to what I initially put in the first request.

My test suite currently looks like:

First Request:

var headerValue = postman.setGlobalVariable('Number', headerValue); console.log("Number is: " + headerValue); 

Second Request Header:

Number - {{headerValue}} 

I would expect headerValue to have the value of 'Number' since I have set it as a global variable but it is coming back as undefined. I'm not sure what I am doing wrong.

like image 428
jmcode Avatar asked Feb 21 '17 16:02

jmcode


People also ask

How do I pass header values in Postman?

Postman will automatically add certain headers to your requests based on your request selections and settings. Select hidden at the top of the headers tab for information about what Postman will send with your request. Hover over a header for details about it. Postman will indicate why the header has been added.

How do I create a dynamic variable in Postman?

' In the request URL section, a dynamic variable should be written in {{__}} format. Let's say you have to pass an integer number from 1 to 1000, so for that, you need to add {{$randomInt}}. Like the above example of the number variable, Postman supports so many other dynamic variables as well.


2 Answers

This is how you can do this

If Refresh_token is the header value

postman.setGlobalVariable("refresh_token",postman.getResponseHeader("Refresh_token") ); 

Official Documentation: https://www.getpostman.com/docs/postman/scripts/test_examples

like image 97
Sai Ram Reddy Avatar answered Oct 16 '22 20:10

Sai Ram Reddy


It seems like @Sai's answer does not work is not recommended anymore, since getResponseHeader is deprecated now. The updated code is:

pm.test("First request", function() {     let headerValue = pm.response.headers.get("Number")     pm.globals.set("Number", headerValue); }); 

In the second request go Headers section, add a new header with Number as a key and {{Number}} as a value.

like image 26
Rostyslav Druzhchenko Avatar answered Oct 16 '22 20:10

Rostyslav Druzhchenko