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.

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.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using “Skeleton screen preloading” and “fade-In Animation” to improve UX with Angular 7

GeoTIFF Coordinate Querying with JavaScript

Create an timed undo feature capable of handling simultaneous undos.

Kuoly’s undo feature in action

React is life

Building a Firebase CRUD Service for Angular

Write and Generate Lightning Web Components Code Documentation Using JSDoc

Example JSDoc code documentation for Hello World LWC

Hosting the Hoisting in JavaScript

How do you copy by value a composite data type?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Viplove Mittal

Viplove Mittal

More from Medium

Deep dive into Pattern Matching for Java

HTTP Status code

REST API — the modern way of web-based architecture and design

Decoding JASON Web Token(JWT) using Java