Setting headers in postman via scripts

I was fixing a prod issue for which I created an API only to find out it was a big issue and I will need to call the API multiple times, can’t send the input as a list. Normally I would just write a python script to do the job or even use runner in the postman.
But for security reasons the all requests coming to our servers need some special headers which are calculated by our system and compared. This was a challenge as running a script in java 30 times then copy value to postman was taking quite long. I can not convert the java program to python script because of large dependencies. Then I found the Pre-request script in postman, looked promising seeing the snippets, but the documentation was horrible and did not explain anything. So, here is how you can do a post call and set headers.
- Make sure you can convert auth logic to js or make a server like I did.
Remember:
You can read the request body by: pm.request.body
You can set header by: pm.request.headers.add({key: “key”, value: “value”})
pm.sendRequest({url: 'localhost:8000/test',method: 'POST',body: pm.request.body}, function (err, response) {console.log(response.text());pm.request.headers.add({key: "auth-key", value: response.text()})});
- Here, before I call the api, a new api is called which sends the request body, receives a auth value from it and sets a header.
- p.sendRequest is used to make Http calls. You can also replace the first param of this function to a url string to make a get request.
pm.sendRequest('localhost:8000/test', function (err, response) {console.log(response.text());});
- You can check console below to confirm the script is running fine, response is correct and the header is set correctly.