API Requests and Chaining the Responses using Pre Request and Test scripts in Postman — Part 2 — Params, Headers & Body Tab
Refer to Part 1 of chaining API response in Authorization tab here.
Tip before going through the blog:
Pre-request script tab is useful to generate values before the execution of any API request i.e Pre API request
Tests tab is useful to collect responses from the executed API i.e Post API request
Now, let us see how to use the responses in other tabs — Params, Headers and Body
- Params Tab Example
Step 1: Create page_number variable in environment tab
Here, if the value is going to be constant, current value can be set and reused
Step 2: Assign the created page_number variable to the required parameter in Params tab
Step 3: In any of your first request (here Registration of an user), test script can be written to generate static or dynamic value for this page number variable
let pageNum = Math.random();
pm.environment.set(“page_number”, pageNum);
Step 4: When this API request is executed, the generated value will be stored in environment tab and can be chained/reused in other API requests
Step 5: When the actual API request is hit, the page number will be assigned and results will be returned
2. Headers Tab
This can be static value wherein you can set the Current value or it can be dynamic value that can be generated using Tests scripts
Example 1: Generating response using test scripts:
Step 1: Write test scripts to collect the response and store it in necessary variable
Step 2: When executed, the response will be stored in registration_token env variable
Step 3: Already created env variable( ex: registration_token ) or newly created ones can be imported into Headers Tab
Example 2: Generating static value that can be created and used.
Step 1: Here api_key is created and current value is set as test
Step 2: This variable can be passed in headers tab
3. Body Tab
I will also explain how Pre-request scripts can be used if random data has to be generated and reused in all the requests
Ex: For registering one user and then to login, we need to pass email id as Body parameter and we need random test data for the same.
For generating data even before execution of any request, Pre-request scripts can be used to generate value and can be stored as environment variable
Step 1: Write scripts to generate dummy data in Pre-request script and assign it to environment variable test_email_id
Step 2: Store the same as environment variable as test_email_id in environment tab
Step 3: After executing the API, data will be generated and can be passed as Body parameter
Conclusion: Pre-request scripts and Test scripts are useful for generating data upon execution of requests and collecting responses to chain other requests.
The series of blog on How to chain API responses to other requests will explain how to generate data and also pass the response to other requests without manual intervention every time.