Generic HTTP request
A function that combines multiple HTTP request functions into a single reusable function that can be used with any request.
This function is best used as a include file so it can be reused across multiple SIL script files. The _httpResult struct is used to return all the info/data needed about the call including, if the call was successful or if it failed, what the failure message is, and any data returned from the call.
Note: This script stores the username and passwords being called by this function in a global variable so that this sensitive data is not stored in the script. For more information about these global variables call Persistent Variables see this page.
struct _httpResult {
boolean success;
string message;
string data;
}
string serverUser = getPersistentVar("serverUser");
string serverPass = getPersistentVar("serverPass");
string cloudUser= getPersistentVar("cloudUser");
string cloudPass = getPersistentVar("cloudApiToken");
string authString = "Basic " + base64Encode(cloudUser + ":" + cloudPass);
function generateRequest(string type) {
HttpRequest request;
HttpHeader header = httpCreateHeader("Content-Type", "application/json");
request.headers += header;
if(type == "SERVER") {
HttpHeader authHeader = httpBasicAuthHeader(serverUser, serverPass);
request.headers += authHeader;
} else {
HttpHeader header2 = httpCreateHeader("Authorization", authString);
request.headers += header2;
}
return request;
}
function genericRestCall(string url, string method, string data, HttpRequest request) {
_httpResult result;
if(method == "GET") {
result.data = httpGet(url, request);
} else if (method == "PUT") {
result.data = httpPut(url, request, data);
} else if (method == "DELETE") {
result.data = httpDelete(url, request, data);
} else if (method == "PATCH") {
result.data = httpPatch(url, request, data);
} else {
result.data = httpPost(url, request, data);
}
number statusCode = httpGetStatusCode();
if (statusCode >= 200 && statusCode < 300) {
result.success = true;
}
else {
string msg = "URL: " + url + " <br /> {" + trim(statusCode) + " : " + httpGetErrorMessage() + " : " + httpGetReasonPhrase() + "}";
result.success = false;
result.message = msg;
}
return result;
}
Example Use
include "Includes/genericRest.incl";
_httpResult result = genericRestCall(jiraUrl+"/rest/api/3/issue/"+key+"/properties", "GET", "", generateRequest("CLOUD"));
if(result.success == true) {
myCustomStruct = fromJson(result.data);
//do something with the returned data
} else {
runnerLog(data.message);
//call failed, initiate self destruct sequence
}