A Postman environment is a set of variables that you can reuse in your requests and share with your team. You can reference them in request authentication, query and path parameters, request bodies, and scripts. Variables help you work efficiently, collaborate with teammates, and set up dynamic workflows. You can use environment variables to call the same request against different servers, such as local, stage, or production.
Each environment has its own set of variable values. When you change environments, selecting the correct environment points your request to the correct host (server) with the proper authentication and its defined variables. Global variables come in really handy in cases where you need to use the same variable across several collections.
It’s easy to manually manage Postman environments when you’re only working with one or two of them. However, if you’ve got hundreds of collections and environments, this can be very difficult to effectively manage.
In this post, we’ll show you how you can use the Postman API to programmatically manage your environments.
The /environments endpoint
The Postman API’s /environments endpoint provides the tools you’ll need to programmatically manage your environments:
- GET /environments — Lists all environments you have access to. You can also filter by a
workspaceId
in the query string to only return the given workspace’s environments. - GET /environments/{environmentId} — Gets detailed information about an environment, including its variables (
values
in the response). - POST /environments — Creates a new environment.
- POST /environments/{environmentId} — Replaces an environment with the data passed in the request body. Note that this is a PUT method that replaces the entire environment resource, including its variables. You must send the entire list of variables you want the final environment to have.
- DELETE /environments/{environmentId} — Deletes an environment.
Getting started
We’ll be using Node.js for the following guides, and we’ve included several JavaScript commands, one for each scenario, with basic code that you can run in the command line. You can find the code and its README file in the postman-api-environments-utils GitHub repository.
We’ll also use the Axios library to perform requests against the Postman API. To make it easier, we’ve included some small methods to call the /environments
endpoint. We’ll also use the following methods in the rest of our code:
const getAllEnvironments = async (postmanApiKey, workspaceId) => {
const url = `${POSTMAN_API_BASE_URL}/environments?workspace=${workspaceId}`;
const response = await axios.get(url, getAxiosConfig(postmanApiKey));
return response.data.environments;
};
const getEnvironment = async (postmanApiKey, environmentId) => {
const url = `${POSTMAN_API_BASE_URL}/environments/${environmentId}`;
const response = await axios.get(url, getAxiosConfig(postmanApiKey));
return response.data.environment;
};
const createEnvironment = async (
postmanApiKey,
workspaceId,
environmentContents,
) => {
const url = `${POSTMAN_API_BASE_URL}/environments?workspace=${workspaceId}`;
const response = await axios.post(
url,
environmentContents,
getAxiosConfig(postmanApiKey),
);
return response.data.environment;
};
const updateEnvironment = async (
postmanApiKey,
environmentId,
environmentContents,
) => {
const url = `${POSTMAN_API_BASE_URL}/environments/${environmentId}`;
const response = await axios.put(
url,
environmentContents,
getAxiosConfig(postmanApiKey),
);
return response.data.environment;
};
Scenario 1: Changing a variable’s value in all environments
You have 100 environments that all use the same common
variable and value. You need to change the common
variable’s value in all 100 environments because the server’s changed. However, doing this manually is both time-consuming and extremely error-prone.
Solution
The following JavaScript function uses the Postman API to update the value of a specific variable with a new initial value:
const updateVarByName = async (
apiKey,
workspaceId,
variableName,
variableValue
) => {
//get all the environments
const environments = await getAllEnvironments(apiKey, workspaceId);
let variablesUpdated = 0;
console.log(`Found ${environments.length} environments`);
//find all the environments with the matching variable name and update them
for (const environment of environments) {
console.log(`Processing environment ${environment.id}`);
const environmentDetails = await getEnvironment(apiKey, environment.id);
const variable = environmentDetails.values.find(
(variable) => variable.key === variableName
);
if (variable) {
console.log(
` Updating variable ${variableName} in environment ${environment.id} to ${variableValue}`
);
variable.value = variableValue;
try {
await updateEnvironment(apiKey, environment.id, {
environment: { ...environmentDetails },
});
} catch (error) {
console.error(`Error updating environment ${environment.id}: ${error}`);
process.exit(1);
}
variablesUpdated++;
}
}
return variablesUpdated;
};
This function gets called in the commands/updateVarByName JavaScript file. You can call it from the command line:
âžś updateVarByName git:(main) ./updateVarByName.js --workspaceId=f9e3a0b7-c58a-4596-9faa-610b81b41ef4 --variableName=common --variableValue="value 7"
The response will look similar to the following:
Found 8 environments
Processing environment 856b7283-9663-4a62-88fe-5ac3bb891421
Updating variable "common" in environment from "value 6" to "value 7"
Processing environment 1b23ddd6-ab73-468f-9dc6-911c65af1eee
Processing environment 53f09c0a-9d0c-464e-9115-a54f8a914a0a
Processing environment d108d001-20e2-46c6-beb6-6f6af7c04103
Updating variable "common" in environment from "value 6" to "value 7"
Processing environment 6fab6de0-8be7-471f-9924-7521e97074e0
Processing environment d35a0c2b-9423-4f29-97f1-dc7d5725f3bd
Updating variable "common" in environment from "value 6" to "value 7"
Processing environment 09711565-cec2-4f47-8c16-8f83ec1bf02a
Processing environment aebfed2a-4f69-42ea-ba8a-7b9d110812f0
Updated 3 variables
You’ll also need to set a POSTMAN_API_KEY
environment variable with a valid Postman API key, which the commands use to authenticate with the Postman API.
Scenario 2: Find environments containing a specific variable value
You have many environments where different variables use a token
value. The token’s value has changed and now you need to manually check and update all of your environments.
Solution
The following is a function that lists all the variables (variable
) that contain a given value (variableValue
) in a workspace’s environments:
const listEnvsWithVarValue = async (apiKey, workspaceId, variableValue) => {
//get all the environments
const environments = await getAllEnvironments(apiKey, workspaceId);
let variablesFound = 0;
console.log(`Found ${environments.length} environments`);
//find all the environments with the matching variable value
for (const environment of environments) {
const environmentDetails = await getEnvironment(apiKey, environment.id);
const variable = environmentDetails.values.find(
(variable) => variable.value === variableValue
);
if (variable) {
console.log(
`Found variable "${variable.key}" in environment "${environmentDetails.name}" (${environment.id}) with value "${variableValue}"`
);
variablesFound++;
}
}
return variablesFound;
};
In the postman-api-environments-utils repo, you’ll find a commands/listEnvsWithVarValue JavaScript file. You can call it from the command line to get all of the environments and variable names that contain the given value.
For example, the following command performs a search for the token
variable value:
âžś listEnvsWithVarValue git:(main) ./listEnvsWithVarValue.js --workspaceId=f9e3a0b7-c58a-4596-9faa-610b81b41ef4 --variableValue="token"
The response will look similar to the following:
Found 8 environments
Found variable "auth" in environment "Stage" (c5b7fe12-ad01-4f11-bc29-1b8acc516c27) with value "token"
Found variable "token" in environment "Production" (ea0b1acf-f806-4187-8061-a0b8c577ece0) with value "token"
Found variable "key" in environment "Local" (a937e02a-ed79-41d6-835e-f6df464fa37a) with value "token"
Found 3 variables
Scenario 3: Merge two environments to run a request
You’ve organized your environments as follows:
- Environments with URL variables for your local, stage, and production servers.
- Environments with variables for your “size” business feature. For example, small, medium, big, and large.
- Environments with variables for your “season” business feature. For example, spring, summer, autumn, and winter.
You have an endpoint that requires all of these variables and you want to test the endpoint with all possible combinations. Currently, you can’t select more than one environment in the Postman when running a collection or sending a request.
To solve this in Postman, you’ll need to create environments for all possible combinations. In this scenario, this would require a total of 48 environments—and all of them must be manually maintained if any variables change!
Solution
With the Postman API, you can create an environment for each combination containing all the variables that your tests require. You can test it and then delete it when you’re finished.
The following function merges a list of given environments into a new, single environment created in the defined workspace (workspaceId
):
const mergeEnvironments = async (
apiKey,
workspaceId,
newEnvironmentName,
environmentIdList,
) => {
const allValues = [];
for (const environment of environmentIdList) {
const environmentDetails = await getEnvironment(apiKey, environment.trim());
for (const variable of environmentDetails.values) {
remove(allValues, (item) => item.key === variable.key);
allValues.push(variable);
}
}
const environmentContents = {
name: newEnvironmentName,
values: allValues,
};
try {
const newEnvironment = await createEnvironment(apiKey, workspaceId, {environment: environmentContents});
const newEnvironmentDetails = await getEnvironment(apiKey, newEnvironment.id);
return newEnvironmentDetails;
} catch (error) {
console.error(`Error creating environment ${newEnvironmentName}: ${error}`);
process.exit(1);
}
};
In the postman-api-environments-utils repo there’s the commands/mergeEnvironments JavaScript file. You can call it from the command line to merge a comma-separated list of environments you pass, which creates a new environment in the given workspace:
âžś mergeEnvironments git:(main) ./mergeEnvironments.js --workspaceId=f9e3a0b7-c58a-4596-9faa-610b81b41ef4 --newEnvironmentName="Merged environment" --environments=12345678-ba5e72c1-7268-4759-93b3-63ccc77b9a99,12345678-62bc4333-6724-44c0-b2d4-32261f01985e,12345678-ba2f563e-2557-4d2d-bc0c-07ed98ccc10a
The response will look similar to the following:
Created new environment "Merged environment" with ID 12345678-116e-4c5d-be2b-484ca22b9ade and details:
{
"id": "af1f16b4-116e-4c5d-be2b-484ca22b9ade",
"name": "Merged environment",
"owner": "12345678",
"createdAt": "2023-08-30T13:07:04.000Z",
"updatedAt": "2023-08-30T13:07:04.000Z",
"values": [
{
"key": "key",
"value": "token",
"enabled": true,
"type": "default"
},
{
"key": "token",
"value": "token",
"enabled": true,
"type": "default"
},
{
"key": "common",
"value": "value 7",
"enabled": true,
"type": "default"
},
{
"key": "auth",
"value": "token",
"enabled": true,
"type": "default"
}
],
"isPublic": false
}
How are you managing your environments?
The Postman API provides full CRUD capabilities that let you programmatically manage your environments. In this post, we’ve covered just some of the possible scenarios and solutions with the Postman API with JavaScript.
Do you have any use cases related to environments that require managing them programmatically? We would love to hear about it—so let us know in a comment below!