API Requests and Chaining the Responses using Test scripts in Postman — Part 1 Authorization Tab
Postman is an API platform for building and using APIs. It gives the features of collections, test scripts which help in storing variables that can be reused.
Every HTTP requests have four main elements — An HTTP method, Request type (GET, PUT, POST, DELETE), Request HEAD/OPTIONS and Request Body.
Problem statement:
How to pass dynamically generated response from one request and pass it on to other requests — i.e chaining the response from one request to another
Solution:
Step 1: Create an API collection in postman
Step 2: Create an environment for that collection which helps in reusing the variables within that environment.
Ex: If you have an environment added as Prod, then all the environment variables declared and values collected will be corresponding to prod requests only.
Step 3: Create a variable in your environment (Here, env name — test_blog , variable name is registration_token)
Step 4: Create your API request for which you want to collect the response variable to chain to other requests
Ex: http://restapi.adequateshop.com/api/authaccount/registration which generates Token that has to be used by Login API — /api/authaccount/login
Step 5: In the same POST request, write these test scripts and then Submit the request
const response = pm.response.json();
var auth_token = response.data.Token;
console.log(auth_token);
pm.environment.set(“registration_token”,auth_token)
Step 6: You can Console the results by enabling Postman Console
Step 7: This token will be saved in environment variable.
pm.environment.set(“registration_token”,auth_token) takes care of setting the value generated in API response to the variable declared inside the environment here.
Step 8: Now, this token can be chained for other requests.
When Login API is hit which needs the registration token as Auth token, we can set {{registration_token}} in Authorization tab
Step 9: When this API request is submitted, the token will be picked from environment variable and the response will be generated
This explains how the login API uses the response from Registration API through response chaining in Postman
Step 10: Similarly many variables that needs to be reused can be added and chained in other requests.
This is not just applicable for Authorization tab, we can pass variables in Body tab, Params tab etc. (Continued in Part 2 of the Blog)