jmcode
jmcode

Reputation: 541

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.

Upvotes: 44

Views: 61834

Answers (5)

pme
pme

Reputation: 14803

Just as an addition to Rostyslav Druzhchenko's answer. In Postman Client you can add this directly in the Tests tab: postman ui

Upvotes: 5

Rostyslav Druzhchenko
Rostyslav Druzhchenko

Reputation: 3773

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.

Upvotes: 35

Oleksandr Yefymov
Oleksandr Yefymov

Reputation: 6509

Simple approach with logging of you header before saving it to variable:

let authToken = postman.getResponseHeader("Authorization")
console.log("auth header -> ", authToken)
postman.setEnvironmentVariable("auth", authToken)

Upvotes: 0

Sai Ram Reddy
Sai Ram Reddy

Reputation: 1089

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

Upvotes: 49

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

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

Upvotes: 1

Related Questions