Skip to content

Instantly share code, notes, and snippets.

@knbknb
Last active February 15, 2024 12:28
Show Gist options
  • Save knbknb/3a8b27adb0b378bfffdd9e5579513a04 to your computer and use it in GitHub Desktop.
Save knbknb/3a8b27adb0b378bfffdd9e5579513a04 to your computer and use it in GitHub Desktop.
Postman JS snippets and Utilities
// Display the response in the Visualizer, if it is json
// and if it has a "model" property
// and a "".choices[0].message.content" Property
// (Typical output from OpenAI API and Perplexity APIs)
pm.test(`response is json`, function () {
const response = pm.response.json();
pm.expect(response.model).to.eql(pm.variables.get("model"));
pm.expect( Object.keys(response).length).to.above(0);
content = response.choices[0].message.content
pm.visualizer.set(`
<html>
<body>
<pre>Model used: ${response.model}</pre>
<pre>${content}</pre>
</body>
</html>
`);
});
// Generate a random integer between 1 and 99
const randomNumber = Math.floor(Math.random() * 99) + 1;
// Format with leading zeros (using padStart)
const formattedNumber = randomNumber.toString().padStart(2, '0');
// Set the environment variable
pm.environment.set("random_number", formattedNumber);
pm.environment.set("currentRequestName", pm.request.url.getPath()); //.split('/').pop());
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const day = String(currentDate.getDate()).padStart(2, '0');
const hours = String(currentDate.getHours()).padStart(2, '0');
const minutes = String(currentDate.getMinutes()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
pm.environment.set("postman-now", formattedDate);
// BEARER TOKEN
// This pre-request script on collection level will try to use an existing token to fetch data from mDIS.
// If it does find a token, reuse and refresh it. If login does not succeed: script will login,
// setting a new token or remove the old token from the environment "mdis-v3".
const url = pm.variables.get("baseUrl") + "/api/v1/auth/login";
const scriptname = "Prerequest script" + pm.collectionVariables.get("collectionName");
// a Reques
const echoPostRequest = {
url: url,
method: "POST",
header: [{ key: "Content-Type", value: "application/json" }],
body: {
mode: "raw",
raw: JSON.stringify({
username: pm.variables.get("username"),
password: pm.variables.get("password"),
}),
},
};
/**
* Use an existing token to perform /refresh request on mDIS,
* if it fails, remove the token from env var and collection var.
*
* @param string token
* @param boolean mustGetToken
* @returns boolean mustGetToken
*/
function doSessionRefresh(token, mustGetToken = false) {
refreshRequest = {};
refreshRequest.url = pm.variables.get("baseUrl") + "/api/v1/auth/refresh";
refreshRequest.header = [
{ key: "Content-Type", value: "application/json" },
{ key: "Authorization", value: `Bearer ${token}` },
];
request.method = "GET";
pm.sendRequest(refreshRequest, function (err, res) {
if (err) {
console.info(`${scriptname}, ${refreshRequest.url}: Network Error when trying to refresh with existing token:`, err);
mustGetToken = true;
// reset existing junk to make sure
pm.collectionVariables.unset("currentAccessToken");
pm.environment.unset("currentAccessToken");
} else {
let response = res.json();
// promote collection var to env var to make sure
// console.info(`Response from ${refreshRequest.url}`, response);
if (response.token) {
pm.environment.set("currentAccessToken", response.token);
mustGetToken = false;
} else {
console.info("Preexisting token was unusable:", response.token);
pm.collectionVariables.unset("currentAccessToken");
pm.environment.unset("currentAccessToken");
mustGetToken = true;
}
//console.log(`pm.environment.get('currentAccessToken'): ${(pm.environment.get('currentAccessToken')).substr(0,6)}...`)
}
});
return mustGetToken;
}
let mustGetToken = true;
let token = pm.variables.get("currentAccessToken");
// console.info("token from env var 'currentAccessToken'", token);
// there might be an existing token but might be from different baseUrl, username, coll/env var...
if (typeof token != "undefined" && typeof token == "string" && token.length === 32) {
// check if token is valid for endpoint baseUrl/api/v1/refresh
// console.info("found preexisting env var 'currentAccessToken', check if it still works", token);
mustGetToken = doSessionRefresh(token, false);
}
if (mustGetToken === true) {
console.info(`${scriptname}: ${url}: Token missing or not accepted for session-refresh: Will get new token..., overwrite env-var "currentAccessToken"`);
pm.sendRequest(echoPostRequest, function (err, res) {
if (err) {
console.error(scriptname, err);
} else {
let response = res.json();
pm.environment.set("currentAccessToken", response.token);
}
});
}
const utils = {
checkToken: function(pm){
var url = pm.variables.get('baseUrl') + "/api/v1/auth/login";
const sendLoginRequest = {
url: url,
method: 'POST',
header: 'Content-Type:application/json',
body:
{
mode: 'urlencoded',
urlencoded: [
{ key: "username", value: pm.variables.get('username') },
{ key: "password", value: pm.variables.get('password') },
]
}
};
var getToken = true;
let tokenVariable = pm.variables.get('currentAccessToken');
if (! tokenVariable) {
console.info(url + ': Token missing, will get new token...')
} else {
getToken = false;
console.info(url + ': Token is good (msg from collection-level pre-req-script)');
}
if (getToken === true) {
pm.sendRequest(sendLoginRequest, function (err, res) {
if (err) {
console.log(err);
} else {
//console.log('Saving the token')
var responseJson = res.json();
pm.environment.set('currentAccessToken', responseJson.token)
}
});
}
},
postman_now: function(pm) {
const now = new Date().toISOString().replace(/:/g, '-').replace(/-\d\d\.\d+Z/g, '');
pm.environment.set("postman-now", now);
},
save_path_variables: function(pm, var_name) {
/* array of path variables */
const path_variables = JSON.parse(JSON.stringify(pm.request.url));
let idx = 0;
for (prop of path_variables.variable){
if (prop.key === var_name && Number.isInteger(prop.value)){
pm.environment.set(`pathvar_${prop.key}`, prop.value)
}
idx++;
}
},
/* requires that host is in allowed domains, and Postman feature "Capture Requests" must be enabled (see status bar) */
};
utils.checkToken(pm);
utils.postman_now(pm);
// does not really work in Postman, but I might use it as a reference later
// GPT-4
pm.sendRequest("http://example.com/api/data", function (err, response) {
console.log(response.json()); // Log the response for debugging
var condition = response.json().condition; // Assuming 'condition' is a boolean in the response
if(condition) {
// If condition is true, set an environment variable to indicate cancellation
pm.environment.set("cancelRequest", true);
} else {
pm.environment.set("cancelRequest", false);
}
});
// Gemini Advanced code
pm.sendRequest({
url: 'https://api.example.com/user/status',
method: 'GET'
}, function (err, response) {
if (err) {
console.log(err);
} else {
let data = response.json();
if (data.userStatus !== 'active') {
console.log("User inactive. Aborting request");
postman.setNextRequest(null);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment