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?

Upvotes: 45

Views: 70622

Answers (9)

stackPusher
stackPusher

Reputation: 6512

For anyone on Postman > 10.0 that is having trouble getting this to work, make sure you don't also have the header set but disabled in the "Headers" tab of your request, otherwise the actual request will be missing the header when using pm.request.headers.add or pm.request.headers.upsert

Upvotes: 0

Prince Billy Graham
Prince Billy Graham

Reputation: 3578

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")}`)

Upvotes: 14

attaboyabhipro
attaboyabhipro

Reputation: 1648

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

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

Upvotes: 13

dsicari
dsicari

Reputation: 730

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

Upvotes: 43

ishegg
ishegg

Reputation: 9927

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'
});

Upvotes: 27

Satheesh M
Satheesh M

Reputation: 221

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

Upvotes: 4

J.Lin
J.Lin

Reputation: 1250

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).

Upvotes: 10

Add080bbA
Add080bbA

Reputation: 1876

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}}

Upvotes: 1

Dragos Durlut
Dragos Durlut

Reputation: 8098

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);
});

Upvotes: 9

Related Questions