Saving a Postman header value into a variable throughout requests in a collection
Solution 1
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
Solution 2
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.
Solution 3
Just as an addition to Rostyslav Druzhchenko's answer. In Postman Client you can add this directly in the Tests tab:
Solution 4
No, try this way. For postman, if you want to set environment or global variable just use (key,value ) pattern this way-
postman.setEnvironmentVariable(key,value) or
postman.setGlobalVariable(key,value)
and finally grab them using {{key}}
var headerValue = ”your value goes here”;
postman.setGlobalVariable('Number', headerValue);
and use {{Number}} on your sub subsequent request header
Admin
Updated on January 28, 2021Comments
-
Admin over 3 years
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.
-
Admin about 7 yearsCurrently getting a 'Number' is not defined doing it this way in the console still
-
Admin about 7 yearsIs there a postman.getHeader method or a method that is similar to that? I'm trying to get the value of a header in my header request instead of hard coding it in the test suite
-
Always Sunny about 7 years@jmcconnell
postman.getResponseHeader("Content-Type"); //Note: the getResponseHeader()
method returns the header value, if it exists. and more about methods here getpostman.com/docs/testing_examples -
SGT Grumpy Pants over 4 yearsThis answer uses code that is now deprecated. You should use
pm.globals.set("Number", pm.response.headers.get("Number"));
. -
Miquel Canal over 3 yearsThis should be accepted answer as of Postmant 7.34.0
getResponseHeader
does not exist onpm
object.