Created
December 5, 2022 11:21
-
-
Save liamwye/f1a7f610bb36e52c34b8cdd76d2fd733 to your computer and use it in GitHub Desktop.
Code snippet to save Postman path variables as local variables. These variables can then be consumed in a request body or test.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Store path variables in a local variable, <collection variable: $pathVariablePrefix><path variable name>. | |
*/ | |
// Get all path variables for use in the request body. | |
let pathVariables = pm.request.url.variables.all(); | |
if (pathVariables.length > 0) { | |
let pathVariablePrefix = pm.collectionVariables.get('$pathVariablePrefix'); | |
// Loop through the path variables and build out an associative array of [key] = value. | |
pathVariables.forEach((variable) => { | |
// Define the local variable name. | |
let variableName = pathVariablePrefix + variable.key; | |
// Set the value and log it in the console for debugging purposes. | |
pm.variables.set(variableName, variable.value); | |
console.log(`Added, "${variableName}" for path var "${variable.key}"`, variable.value); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment