Pre-requests in rescue
Setting pre-request to save multiple clicks for API testing in Postman
Most application will have an oauth2 authentication mechanism which typically has an endpoint which provides an accessToken which needs to be passed by subsequent API calls.
In our simple example let us consider 2 endpoints
- Authentication which provides the accessToken — /authenticate
- An API that will serve our request in this case print Hello World — /hello
It is a real pain in the butt when you have multiple apis to call, so postman has introduced a concept call Pre-request Script which will run before the actuall api call. In our example we would call the authenticate enpoint in the pre-request script of the /hello api request
Step 1 : Write a pre-request script to fetch token and store it in a global variable
We would call the authenticate endpoint and extract the accessToken from the response in a global variable (token)
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"username": "javainuse",
"password": "password"
});
var requestOptions = {
url:"http//localhost:8080/authenticate",
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
//setting he token in a global variable
pm.sendRequest(requestOptions, function (err, response) {
pm.environment.set("token", response.json().accessToken);
});
Step 2: Use the token which was fetched by the pre-request in the API call
go to Autherization tab -> Type (Bearer Token) -> use the global variable in which you have saved the accessToken
Step 3: Fire it!
Now run the API and let postman do everything for you