Welcome to this week's TWIL session, where our resident expert Katie shares insights on Postman Environments, Variables, & Faker as well as the utility of Postman Pre-Request Scripts. Grasp the power of Postman's environment management and dynamic data generation to enhance API testing efficiency. Katie's contributions this week provide a practical walkthrough on configuring Postman to seamlessly switch API contexts and exploit its dynamic variable feature to simulate real-world data. Furthermore, learn how to leverage pre-request scripts to automate setup and testing processes, ensuring your requests are executed in the exact environment state required. Join us on a journey of micro-learning with Postman's tools that promise to refine your software development practices.
Postman Environments, Variables, & Faker
Our collections often rely on Postman's environments and environment variables (e.g., using base_url
in request URLs so that requests can easily switch between APIs), but there is a lot that can be done with Postman's environments, variables, and dynamic variables (powered by Faker).
To access an environment variable in a pre-request script or test:
pm.environment.set("variable_name", "I'm set in the environment now!");
pm.environment.get("variable_name");
This can be used to set and use local variables as well (including, for example, between a pre-request script and test):
pm.variable.set("local_variable_name", "I'm specific to the request I'm in.");
pm.variable.get("local_variable_name");
Postman has dynamic variables that are evaluated in the request:
// request body
{
"name": "{{$randomName}}",
"email": "{{$randomEmail}}",
"favoriteColor": "{{$randomColor}}"
}
// pre-request script / test
pm.variables.set("notes", "{{$randomLoremParagraph}}")
If you need to access the value of an evaluated dynamic variable (since otherwise each instance will be different), you can use replaceIn
:
let firstName = pm.variables.replaceIn("{{$randomFirstName}}");
let lastName = pm.variables.replaceIn("{{$randomLastName}}");
let fullName = `${firstName} ${lastName}`;
// "{{$randomFirstName}} {{$randomLastName}}" would result in a full name with a
// different first and last name than set for firstName and lastName
- Tools
- Postman
Postman Pre-Request Scripts
Postman's pre-request scripts can be helpful for a variety of setup, running, and testing uses. For example, ensuring that a given user is logged in (or out) before a request is sent, creating a record specifically for a deletion request, or setting a variable for use in a request based on some API response, all without depending on any other Postman requests.
Logging In
+ Storing Tokens
pm.sendRequest({
url: `${pm.environment.get("base_url")}/login`,
method: "POST",
body: {
mode: 'raw',
raw: JSON.stringify(
{
"email": pm.environment.get("user_email"),
"password": pm.environment.get("password")
}
)
}
}, function (err, res) {
let response = JSON.parse(res.json());
pm.environment.set("access_token", response.tokens.access_token);
pm.environment.set("refresh_token", response.tokens.refresh_token);
});
Clearing Stored Tokens
pm.environment.set("access_token", "");
pm.environment.set("refresh_token", "");
Creating for Deletion
+ Setting Local Variable for Request URL
// If the request returns the deleted object, saving the creation values in local
// variables can be utilized for testing the response; it may not be useful otherwise
let thingName = "{{$randomNoun}}"
pm.variables.set("thing_name", thingName);
// Create thing for deletion
pm.sendRequest({
url: `${pm.environment.get("base_url")}/api/things`,
method: "POST",
header: {
"Authorization": `Bearer ${pm.environment.get("access_token")}`
},
body: {
mode: 'raw',
raw: JSON.stringify({ "name": thingName })
}
}, function (err, res) {
// Set local variable `delete_id` for use in request URL
let response = JSON.parse(res.json());
let thingId = response.data.id;
pm.variables.set("delete_id", thingId);
});
Then, our delete request URL can be something like this, without needing to maintain delete_id
in the environment or having worry about which records are being/have already been deleted:
{{base_url}}/api/things/{{delete_id}}
- Tools
- Postman