Thursday 30 December 2021

POSTMAN PRE-REQUEST-SCRIPT

 POSTMAN PRE-REQUEST-SCRIPT


POSTMAN provides many features for clubbing ,testing and running API through it. There are many features which can be handy while testing or developing REST APIs.

Pre-Request-Script feature is one the core feature which can be used for setting Token for subsequent request. We can make use of environment variable and set same in header in a collection.

Code snippet for same is ::

CASE 1: When request body contains raw data type.

pm.sendRequest({
url: 'http://localhost:8080/authenticate',
method: 'POST',
header: 'Content-Type:Application/json',
body: {
mode: 'raw',
raw: JSON.stringify({
"username":"admin",
"password":"password"
})
}
}, function (err, res) {
console.log(res.json());
pm.environment.set("authorization", "Bearer " + res.json().token);
});


Now in any request we can set header by setting key and value as "Authorization"  {{authorization}} 


CASE 2: When request body contains formdata type.


const reqObj = {

'method': 'POST',
'url': 'http://localhost:8080/authenticate/token',
'body': {
'mode': 'formdata',
'formdata': [
{'key':'grant_type', 'value':'password'},
{'key':'client_id', 'value':'2'},
{'key':'scope', 'value':'*'},
{'key':'client_secret', 'value':'Tjkjkjk'},
{'key':'username', 'value':'anoop'},
{'key':'password', 'value':'password'}
]
}
};
pm.sendRequest(reqObj, (error, response) => {
if (error) throw new Error(error);
console.log(response.json().access_token);
pm.environment.set("TOKEN",response.json().access_token);
});

Similar to the above request , in this also we can set value dynamic with {{TOKEN}}


CASE 3: Can also add below code under Test tab and set Collection Variable as X-Auth-Token useful for all the request under collection.


var res = pm.response.json();
pm.environment.set('X-Auth-Token', res.access.token.id);
pm.collectionVariables.set('X-Auth-Token',res.access.token.id);

console.log(res.access.token.id);




No comments:

Post a Comment