DEV Community

Cover image for Writing pre-request scripts in postman
JOOJO DONTOH
JOOJO DONTOH

Posted on

Writing pre-request scripts in postman

A pre-request script (PRS) is basically a function or code logic that runs before a server request. You may be thinking to yourself "where and when would I ever need this?🤨"
Let's say you were working on a server that has endpoints which require the attachment of jwt tokens to each endpoint. It will be counter-productive to manually use the sign-in/login endpoint to always retrieve the token after login and then assign it to the headers of the endpoints you want to use. This gets even more tedious when the token expires in a very short time.
So to increase productivity in a situation like this, pre-request scripts help to run the sign-in/login endpoint while setting the token and other environmental variables we need to run our request.
PRSs are written in the "pre-req." tab for whichever request you want to run and they are written in javascript. Once code is put under the "pre-req." tab, there should be a green glow beside the tab indicator as shown below.
Alt Text
PRSs can also be assigned to entire postman collections or folders to allow them run before every request in the collection/ folder. This can be done by clicking on the ellipses beside the collection and then clicking the edit tab.
Alt Text
In a PRS, postman has made a pm object available that contains various properties and methods.
Alt Text
An example to fit the use case I presented earlier can be seen below

const devOnline = <your serverlink>
const username = "joojodontoh@gmail.com"
const passwordStg = "*****"

pm.sendRequest({
    url: devOnline + '/user/signin',
    method: 'POST',
    header: {
        "Client-key": pm.globals.get('Client-key'),
        "Content-Type": "application/json"
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            email_phone: username,
            password: passwordStg
        })
    }
}, function (err, response) {
    if (err) {
        return console.error(err)
    }


    const { code, message, data } = response.json()
    console.log('data:', data)


    pm.globals.set('UID_STG', data.uid)
    pm.globals.set('U4T_STG', data.token)
})
Enter fullscreen mode Exit fullscreen mode

The pm object can be used to set and get environmental/global variables; pm.globals.set('UID_STG', data.uid) & pm.globals.get('UID_STG'). It can also be used to send requests with its sendRequest method.
Just like writing code anywhere else, there are times when you'll need to debug the PRS for errors via a console. Holding down (CMD/CTRL + ALT + C) will automatically open the postman console for you.
Alt Text
Try writing a pre request script and share your experience with it.

Top comments (0)