Postman is not adding headers programmatically

5.2k Views Asked by At

Using Postman 5.5.0 on Ubuntu 16.04. I have the following pre-request script defined for my entire collection. My goal is to set a header on each request at the collection level without having to add it manually.

console.log('adding "Authorization: Token {{apiToken}}" header to current request');

pm.request.headers.add({
    key: 'Authorization',
    value: 'Token {{apiToken}}'
});
console.log(pm.request.headers);

I also tried setting the header value directly with value: 'Token '+pm.environment.get('apiToken').

Neither approach actually adds it to the requests. The pm.request.headers is reporting that it's there, but come show time, it sure ain't. Here is the console output:

no auth header sad panda

I also tried adding disabled: false to the object passed to add, based on what's there if I add the header to a single request manually.

What's going on?

1

There are 1 best solutions below

5
On

If you're trying to use the {{...}} syntax in the Pre-request Script or Tests tab it's not going to set the environment variable value for you, as this can only be used in the URL, Headers and the Request body.

The way that you had it in your code, would always just be setting the Authorization key as the string - 'Token {{apiToken}}'.

A completely horrible way of getting the value would be this:

pm.request.headers.add({
    key: 'Authorization',
    value: `Token ${pm.environment.get('apiToken')}`
});

But again that's not going to set the header at the collection level.

You can add it as a global variable at the collection level in a pre-request script - This can then be added to each request.