'Add header to every request in Postman in pre-request script

I want to automatically add a header to every request in my whole collection using this pre-request script:

pm.request.headers.add({
    'key': "myvar",
    'value': pm.environment.get("myvar")    
});

myvar is an environment variable.

Unfortunately, it doesn't work. Did I miss something?



Solution 1:[1]

For those who are trying it on postman ~ 7.10.0, you can add headers programmatically in a pre-request script, into the request or into the collection (into collection will add headers to all requests inside collection).

pm.request.headers.add({ 
    // These keys appears when you set a header by hand. Just for fun they are here
    disabled: false,
    description:{
        content: "DescriptionTest",
        type: "text/plain"
    },
    // Your header, effectively
    key: 'KeyTest', 
    name: 'NameTest', 
    // If you set a variable you can access it
    // HeaderTest here has value="ValueHeaderTest"
    value: pm.collectionVariables.get("HeaderTest")
});

The code snippet generator will not show the added header:

GET /get_info.php HTTP/1.1
Host: 192.168.15.25:8001
Content-type: application/json
User-Agent: PostmanRuntime/7.19.0
Accept: */*
Host: 192.168.15.25:8001
Accept-Encoding: gzip, deflate
Connection: keep-alive

But the Postman Console will:

GET /get_info.php HTTP/1.1
Content-type: application/json
KeyTest: ValueHeaderTest
User-Agent: PostmanRuntime/7.19.0
Accept: */*
Host: 192.168.15.25:8001
Accept-Encoding: gzip, deflate
Connection: keep-alive

Solution 2:[2]

As of Postman v7.0.9, this is now possible by adding a Pre-request Script on a collection.

To do this, go to your collection, right-click it, select Edit, and go to the Pre-request Scripts tab, where you can add your snippet, i.e.:

pm.request.headers.add({
  key: 'X-HEADER-TEST',
  value: '1'
});

Solution 3:[3]

This certainly works. Loose the inverted commas on key and value

pm.request.headers.add({
    key: "myvar",
    value: pm.environment.get("myvar")    
});

Solution 4:[4]

Looks like pm.request.headers.add() doesn't currently update the request being sent. It's been marked as a feature request: https://github.com/postmanlabs/postman-app-support/issues/4631

You might already know that you can create pre-set headers (from the Presets dropdown) to make setting your headers a little bit easier. And there's a couple options under Settings to include specific headers. But these suggestions don't automatically add a header to every request in the whole collection like you're asking about.

UPDATE: Postman added support for this in Postman App (v7.0.9).

Solution 5:[5]

This copied from here, but it worked for me

https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990

pm.sendRequest({
    url: "https://mydomain/ers/config/endpoint",
    method: 'GET',
    header: {
        'content-type': 'application/json',
        'accept': 'application/json',
        //'x-site-code': pm.environment.get("x-site-code")
        'X-CSRF-TOKEN': 'fetch'
    },
    body: {
        mode: 'raw'//,
        raw: JSON.stringify({ email: pm.environment.get("email"), password: pm.environment.get("password") })
    }
}, function (err, res) {

    pm.environment.set("X-CSRF-TOKEN", "Bearer " + res.json().token);
});

Solution 6:[6]

I think may be you can try this way :

  // Add or update an existing header

 pm.request.headers.upsert({
 'key': "myvar",
 'value': pm.environment.get("myvar") 
 });

This was updated in Postman App (v7.0.9). For more reference you can refer to : https://github.com/postmanlabs/postman-app-support/issues/1947

Solution 7:[7]

Just add it in this way:

pm.request.headers.add("x-api-key: value")

may using environment variable:

pm.request.headers.add(`x-api-key: ${pm.environment.get("x-api-key")}`)

Solution 8:[8]

In test section of login, use this script to remember token in Environment

var jsonData = JSON.parse(responseBody);

tests["Body contains result"] = responseBody.has("result");

var result = jsonData.result

tests["result contains user"] = result.user !== null
var user = result.user
tests["result contains token"] = result.token !== null
var token = result.token
var accessToken = token.accessToken
var refreshToken = token.refreshToken

postman.setEnvironmentVariable("accessToken", accessToken);
postman.setEnvironmentVariable("refreshToken", refreshToken);

in every call wihich requires token, use token like this in header section

Authorization = Bearer {{accessToken}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dsicari
Solution 2 ishegg
Solution 3 attaboyabhipro
Solution 4 akmozo
Solution 5 Dragos Durlut
Solution 6 Satheesh M
Solution 7 princebillyGK
Solution 8