/ postman

Setting up a Pre-request script in Postman

This can be really helpful for those who use Postman to test and develop their APIs.

There may be certain situations where one might need to send some custom headers or other params but they need to get it in another request first.
For example I needed to send Authorization header everytime for the requests, and there was a timeout for these tokens needed to be sent. Means I couldn't just sign in a user today and use it forever, I needed to update it every half an hour.
So what I did was to add a custom pre-request script that would hit the signin url and set a global variable in postman to be used with the request thereafter.
The header setup with the variable can be done like this: postman
And in the pre-request tab, we can put this:

pm.sendRequest({
    url: 'http://localhost:3000/api/v1/users/sign_in',
    method: 'POST',
    header: {
        'content-type': 'application/json',
        'accept': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ user: {
            email: 'abcd@gmail.com',
            password: "abcdef"
        }})
    }
}, function (err, res, xhr) {

    var token = res.headers.get('authorization');
    console.log(token);
    pm.globals.set("token", token);
    pm.environment.set("otherVariable", res.json().someKey);
});

This will certainly put the need of sign in before every other request away.

Hope it helps.