Extracting Data from Responses and Chaining Requests
Update: If you want to dig deeper into chaining requests, check out our related post called How to Make Money Using Postman: Chaining Requests.
Postman lets you write scripts that run before/after you receive a response from the server. You can do practically anything in these scripts. The pre-request and test scripts run inside a sandbox and Postman enable the Postman object to interact with the main Postman context.
This opens up a number of new possibilities. One of them is extracting values from the response and saving it inside an environment or a global variable. Environment and global variables let you keep track of everything that affects the APIs state. Some examples of common variables you would use with an API are session tokens and user IDs.
The flow while working with variables currently goes like this:
- Send a request from Postman
- Receive the response and select and copy a value from the response body or the header
- Go to the environment manager
- Set the variable value
- Hit submit
Lets go through an example which will illustrate this in more detail:
1. Create and select an environment
For this example, we’ll create and set a blank test environment.
2. GET request to get response body
This request returns a JSON body with a session token. For this dummy API, the token is needed for a successful POST request on the ‘/status’ endpoint. To extract the token, we need the following code.
var jsonData = JSON.parse(responseBody); postman.setEnvironmentVariable("token", jsonData.token);
Add this to the test editor and hit send. Hover over the quick look window (q) to check that the variable “token” has the value extracted from the response
3. POST request with the previous session token
To send the token, we need to set it as part of the POST request. Let’s add a form-data variable to the ‘/status’ request.
On hitting send, Postman sends the token along with the request.
Test scripts let you extract variables and chain together requests in any way you like. As request variables work everywhere, you can build a sequence of API calls which exactly mirror your use case.
You can download the sample collection and import it inside Postman. Check out the docs for more Postman features. There are more tutorials planned in this series. Keep a tab on this blog as well as the Twitter account for more tips and tricks. And do get the Jetpacks upgrade!
What’s your experience working with test scripts? Leave a comment to let us know.