I came across a situation where I wanted to set a cookie in headers of a request dynamically using the current timestamp. I use Postman, and found that it already has newly introduced a way to modify request before sending it.
Pre-request scripts are really helpful when you want to dynamically set your request attributes.
Their Sandbox is a great tool to make web development easier.
So, coming back to the challenge, setting headers dynamically in postman.
First let's start with looking at the way we can get headers of a request.
How to get headers
It is simple, from their docs:
pm.request.headers
This code would return a list of headers in key-value pairs.
Now, how do we set a header, use
pm.request.headers.upsert({key: yourKeyName, value: yourValueName})
That's it. upsert
is better than using add
, as add
would just add header key but now the vaue, upsert
adds the key value pair, but also if the key is already present, it would update the value for that key withe the newly provided one in pm.request.headers.upsert
method.
How to get timestamp
var date = new Date();
var tStamp = date.getTime();
now combining both code snippets to set headers, we have:
var tStamp = date.getTime();
pm.request.headers.upsert({
key: "time_stamp",
value: tStamp
});
And it is done, now the request would have header time_stamp
set with the request's timestamp set as value.
To check if the headers are set correctly, just console out the headers as pm.request.headers
.
Top comments (0)