Manage your Postman environments with the Postman API
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 at 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.
For example, you can use a url
environment variable to define a server’s URL. You can then use it in your requests using the {{url}}/path-to-your-endpoint
request format. Or you could use a token
variable to set a request’s Authentication: Bearer {{token}}
authentication. For more information about Postman’s environment variables, see the Postman documentation for adding environment variables.
Using the Postman API’s environments endpoint
The Postman API’s environments endpoint provides all the tools you’ll need to programmatically manage your environments:
- Get all environments: Lists all the environments you have access to. You can also filter by a
workspaceId
in the query string to only return the given workspace’s environments. This endpoint returns only basic information about all environments and doesn’t list the environments’ variables.
- Get an environment: Gets detailed information about an environment, including its variables (
values
in the response).
- Create an environment: Creates a new environment.
- Update an environment: 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 an environment: Deletes an environment.
Managing your Postman environments
When you only use one or two environments, manually managing them is easy. But if you’ve got hundreds of collections and environments, this can be very difficult to effectively manage.
In this blog post, we’ll show you how you can use the Postman API to programmatically manage your environments.
Getting started
We’ll be using Node.js for these guides, and we’ve included several JavaScript commands, one per 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 has changed. Manually updating all 100 environments 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" 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. Get all environments that contain a specific variable value
You have many environments where the token
value is used in different variables. The token’s value has changed and now it needs to be updated in all of your environments.
In Postman, you’ll need to manually review all of your environments. This includes checking all the variables and updating the token’s value.
Solution
We can use the Postman API to easily solve this workflow. The following is a simple 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 GitHub repository you can 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. Here’s an example of running this command to find the token
variable value:
➜ listEnvsWithVarValue git:(main) ./listEnvsWithVarValue.js --workspaceId=f9e3a0b7-c58a-4596-9faa-610b81b41ef4 --variableValue="token" 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 request.
To solve this in Postman, you need to create environments for all possible feature combinations. In the given scenario, this requires 48 total environments—and all of them must be manually maintained if any of their variables change!
Solution
Using the Postman API, you can create a single environment for each combination that contains all the variables that the test requires. You can then test it and delete it after 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 GitHub repository 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 and create 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 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 environments?
The Postman API provides full CRUD capabilities that let you programmatically manage your environments. In this blog post, we’ve shown you just some of the possible scenarios and their solutions using the Postman API with JavaScript code.
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!
want to call|hit default api, after environment change in postman, how it will be possible?
Please contact our support team at http://www.postman.com/support and they’ll be able to help you.