Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Programmatically persist the current values to initial values of environment variables.
let headers = {'X-Api-Key' : ''};
headers[`X-Api-Key`] = String(pm.variables.get("postman_api_key"));
// Note: Update the environment UID if no longer sync
const postman_api_url = "https://api.getpostman.com/environments/" + pm.environment.get("uid");
let requestOptions = {
url: postman_api_url,
method: 'GET',
header: headers
}
// retrieve first the complete set of current environment data
pm.sendRequest(requestOptions, (error, response) => {
if (error) {
console.error("Error retrieving current environment data: " + error)
} else {
let body = response.json()
console.log("Current Environment: " + JSON.stringify(body))
// start updating target environment variables
let index = body.environment.values.findIndex((item) => {
return (item.key === "firstname")
})
if (index != -1) {
body.environment.values[index].value = String(pm.environment.get("firstname"));
} else {
let vars = {key: '', value: ''};
vars.key = 'firstname';
vars.value = String(pm.environment.get("firstname"));
console.log("vars: " + JSON.stringify(vars));
body.environment.values.push(vars);
}
index = body.environment.values.findIndex((item) => {
return (item.key === "lastname")
})
if (index != -1) {
body.environment.values[index].value = String(pm.environment.get("lastname"));
} else {
let vars = {key: '', value: ''};
vars.key = 'lastname';
vars.value = String(pm.environment.get("lastname"));
console.log("vars: " + JSON.stringify(vars));
body.environment.values.push(vars);
}
console.log("New Environment Variables: " + JSON.stringify(body))
requestOptions = {
url: postman_api_url,
method: 'PUT',
header: headers,
body: {
mode: 'raw',
raw: body
}
}
//console.log("JSON.stringify(): " + JSON.stringify(requestOptions));
pm.sendRequest(requestOptions, (error, response) => {
if (error) {
console.error("Error updating current environment: " + error)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment