Pre-requests in rescue

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
Screenshot 2021-05-26 at 11.36.12 PM.png
  • An API that will serve our request in this case print Hello World — /hello
Screenshot 2021-05-26 at 11.37.49 PM.png

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

Screenshot 2021-05-27 at 12.10.10 AM.png

Step 3: Fire it!

Now run the API and let postman do everything for you

Screenshot 2021-05-27 at 12.12.05 AM.png

--

--

--

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

Recommended from Medium

Deployment of React.JS, using AWS S3, CircleCI and Terraform.

Exploding polygons in Snowflake. KaBooom! Visualising Dublin property data in Tableau.

7 Best Security Practices in Python Programming Language

A Quick Look at the TinyFGPA & Lattice Diamond

OpenLiveNFT

gRPC over TLS with Traefik 2.0 on AWS

Codding Project on C language (time converter)— by Anish….

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
Soumik Dutta

Soumik Dutta

More from Medium

What is JWT? How that is working in flutter or webserver?

11 Reasons to Hire Ionic Developers for Your Startup: Must Read

Is There Any Danger in Using Cloud-Based Autocomplete in Software Development?

What is an API why we use it?