Skip to content

Instantly share code, notes, and snippets.

@ml-eds
Last active October 24, 2019 06:58
Show Gist options
  • Save ml-eds/51c5b16d8db479ed4e9fb463e4842043 to your computer and use it in GitHub Desktop.
Save ml-eds/51c5b16d8db479ed4e9fb463e4842043 to your computer and use it in GitHub Desktop.
Postman: Write response values back to environment vars
// Place the following in the "Tests" tab of a request
// Check HTTP status code
tests['Status 200'] = responseCode.code === 200;
// We need valid JSON
var validJSON = false;
var resData = {};
try {
resData = JSON.parse(responseBody);
validJSON = true;
} catch (e) {
console.log({err: e});
}
tests['Valid JSON Response'] = validJSON;
if (!validJSON) {
return postman.setNextRequest(null);
}
// extract values "token" and "user"
var jwtTokenField = resData.token;
var user = resData.user;
tests['jwt token field found'] = (jwtTokenField !== null);
if (jwtTokenField !== null) {
// write token value to environment var jwt
postman.setEnvironmentVariable("jwt", "Bearer "+jwtTokenField);
} else {
postman.setNextRequest(null);
}
tests['user field found'] = (user !== null);
if (user !== null) {
// write user.id to environment var userId
postman.setEnvironmentVariable("userId", user.id);
} else {
postman.setNextRequest(null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment