I am new to Jira API & I am currently creating a google form to create a subtask automatically for any ad-hoc requests attaching to an existing story that is already created manually.
URL: https://<subdomain>.atlassian.net/jira/software/c/projects/<PROJECTID>
STORY CREATED: PROJECTID-XXX
I have the following sample code to test:
function createSubTask(summary, description) {
var URL = 'https://<subdomain>.atlassian.net/rest/api/3/issue';
var username = '<user-name>';
var password = '<api-key>';
var userCreds = "Basic " + Utilities.base64Encode(username + ':' + password);
var data = {
"project": {"key": "PROJECTID"},
"parent": {"key": "PROJECTID-XXX"},
"summary": summary,
"description": description,
"issuetype": {"name":"Sub-task"}
};
var payload = JSON.stringify(data);
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": userCreds,
"muteHttpExceptions": "True"
};
var options = {
"method": "POST",
"headers": headers,
"payload": payload
}
var response = UrlFetchApp.fetch(URL, options);
Logger.log(response);
}
I am getting the following error:
Exception: Request failed for https://<subdomain>.atlassian.net returned code 400. Truncated server response: {"errorMessages":[],"errors":{"project":"Specify a valid project ID or key"}} (use muteHttpExceptions option to examine full response)
Not sure, what I am doing wrong.
"muteHttpExceptions": true
muteHttpExceptions be in the options block and true should be a bool not a string.
I was getting the Specify a valid project ID or key error, then swapped this in the options block and got a response error that was actually the problem.
Use the following payload format. It will fix the problem.
{
"fields": {
"project":
{
"key": "TEST"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
}
Related
Hi everyone recently i have been trying to do a fetch post in app script, from an api called salesbinder(inventory system), i have managed to fetch and pulls all inventory data down, however i have been struggling to post and add document to it and received an error code ->
"Truncated server response: {"message":"Unauthorized","url":"\/api\/2.0\/documents.json","code":401}"
since I am using the same username and password I can assure that the details are correct for the authentication, would appreciate a lot if anyone could help me to solve the problem.
Here are the api documentaion (https://www.salesbinder.com/api/documents/add/) and the code i have been using.
function posting(){
var Username = "{API KEY}"
var Password = "x"
var headers = {
"Authorization" : "Basic " + Utilities.base64Encode(Username+ ':' + Password)
};
var url ='{API URL}'
var data ={
"document":{
"customer_id": 'a93a9e9a-5837-4ec5-9dc7-47cc8cfd84e4',
"issue_date":"2022-05-09",
"context_id":5,
"document_items":[
{
"quantity":2,
"price":134,
"item_id":" b04993fe-7b17-42a1-b5e5-2d34890794c9"
}
]
},
};
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
UrlFetchApp.fetch(url, option);
}
I think that your error message of "message":"Unauthorized" is due to "headers": {headers},. This has already been mentioned in chrisg86's comment.
And also, from this document, it seems that the request body is required to be sent with Content-Type: application/json.
From:
var option = {
"method": "post",
'payload' : data,
"headers": {headers},
};
To:
var option = {
"method": "post",
"payload": JSON.stringify(data),
headers, // or "headers": headers
"contentType": "application/json"
};
Note:
In this modification, it supposes that the values of "Basic " + Utilities.base64Encode(Username+ ':' + Password), data and url are correct. Please be careful this.
I have some issues with an API with oauth2 authentication.
After I get the token, and I want to sent my POST request but it still gives me a 415 error (Unsupported Media Type). I'm sure my payload's fields are good because I tried with postman and it works, but I don't know if I have to JSON stringify the header (the payload I think, but I'm not sure at 100%). I run my code on Google apps script so I thought the problem came from apps script, but I can get the token and send GET request on it.
function post_pers() {
var url = "(my url)";
var data = {
"id": 32,
"nom": "apij",
"prenom": "joseph",
"civiliteLongue": "Monsieur",
"idTypePersonne": "PERSTPHYSIQUE ",
"ligne1Adresse": " ",
"ligne2Adresse": " ",
"ligne3Adresse": " ",
"codePostal": " ",
"commune": " ",
"idPays": "FR",
"iban": " ",
"bic": " ",
"titulaireCompte": " ",
"domiciliationBanque": " ",
"assujettiTva": true,
"mediaPrefere": "Mail",
}
var payload = JSON.stringify(data);
Logger.log("payload; "+payload)
Logger.log("data; "+data)
var header1 = {
"accept": "application/json",
"authorization": "Bearer (my access token)",
"content-type": "application/json"
}
var header = JSON.stringify(header1);
Logger.log("header; "+header)
Logger.log("header1; "+header1)
var options = {
"method": "POST",
"header": header,
"payload": payload
}
var response = UrlFetchApp.fetch(url, options);
Logger.log(response)
}
415 is unsupported media. This is usually due to Content-Type header typos. Your script is stringifying headers, which would make header unreadable by the server. Try
var options = {
"method": "POST",
"header": /*header*/header1,
"payload": payload
}
I am making an application that sends emails from a User as described by this article.
Everything is working as expected, except for when I try to include an attachment. The email sends, but without the attachment. I'm not sure what the problem is as I've tried pretty much everything I could find online. I have made sure the file I am sending is properly encoded in base64.
var message = {
"subject": subject,
"hasAttachments":true,
"body": {
"contentType": "Text",
"content": emailBody
},
"toRecipients": toRecipients,
ccRecipients,
bccRecipients
};
function sendMailRequest(access_token, message, uriSend, file, base64, callback){
const attachments = [{
'#odata.type': '#microsoft.graph.fileAttachment',
"contentBytes": base64
"name": "example.jpg"
}];
// Configure the request
var options2 = {
"url": uriSend,
"method": 'POST',
"headers": {
'Authorization': access_token,
'Content-Type': 'application/json'
},
"body": JSON.stringify({
"message": message,
"SaveToSentItems": "true",
"Attachments": attachments
})
}
Attachments go inside the message JSON, not outside of it. This should work:
function sendMailRequest(access_token, message, uriSend, file, base64, callback) {
const attachments = [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"contentBytes": base64
"name": "example.jpg"
}
];
message["attachments"] = attachments;
// Configure the request
var options2 = {
"url": uriSend,
"method": "POST",
"headers": {
"Authorization": access_token,
"Content-Type": "application/json"
},
"body": JSON.stringify({
"message": message,
"SaveToSentItems": "true"
})
}
...
}
So it seems that Sling (sling.is) updated their API, but never sent out an email with warning or information, so my script is broken. The end goal of my code (which worked fine prior to their update) is to simply post shifts for employees to Sling upon a company event being approved.
I'm running all of this code in google apps script since I need to pull data from a spreadsheet to create the shifts. The code works by first "adding" the shifts to the system, and then secondly "publishing" those shifts so all employees can see them. I managed to figure out how to fix the first part as it seems they switched some basic syntax around. But I can't for the life of me figure out how to fix the second (publishing) part.
Sling doesn't offer any support for their API, so I thought posting here would be my next best bet.
Here's the error I'm receiving:
"Request failed for https://api.sling.is/v1/shifts/sync returned code
500. Truncated server response: {"message": "Oops, an unexpected error occured."} (use muteHttpExceptions option to examine full response)
(line 257, file "Code")"
//CREATE SHIFTS ON SLING
//This is pulling data from google spreadsheet cells
var staff = getByName('Attendants', row);
var start = Utilities.formatDate(getByName('Date', row),
ss.getSpreadsheetTimeZone(), "YYYY-MM-dd") + "T" +
Utilities.formatDate(getByName('Starting Time of Attendants', row),
ss.getSpreadsheetTimeZone(), "H:mm") + ":00.000-04";
var end = Utilities.formatDate(getByName('Date', row),
ss.getSpreadsheetTimeZone(), "YYYY-MM-dd") + "T" +
Utilities.formatDate(getByName('Ending Time of Attendants', row),
ss.getSpreadsheetTimeZone(), "H:mm") + ":00.000-04";
var notes = getByName('City', row) + ", " + getByName('Event Type', row)
var payload = {
"available": true,
"dtstart": start,
"dtend": end,
"location": {
"id": 1022310
},
"position": {
"id": 1022302
},
"summary": notes,
"user": {
"id": 1
}
};
var headers = {
"Authorization" : "9e632842f4e61927336337f1aa65b75c"
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'headers' : headers,
'payload' : JSON.stringify(payload)
};
for(i=1; i<=staff; i++){
UrlFetchApp.fetch("https://api.sling.is/v1/shifts?
ignoreConflicts=false&publish=true", options);
}
// All of that ^^ works
var payloadtwo =
{
"summary": notes
};
var optionstwo = {
'method' : 'post',
'contentType': 'application/json',
'headers' : headers,
'payload' : JSON.stringify(payloadtwo)
};
UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
I even tried completely removing the payload (body) parameter from the JSON options.
var payloadtwo = {
"summary": notes,
"dtstart": "2018-11-07T12:00:00:00.000-04",
"dtend": "2018-11-09T12:00:00:00.000-04"
};
var optionstwo = {
'method' : 'post',
'contentType': 'application/json',
'headers' : headers
};
UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
and then it says
"Request failed for https://api.sling.is/v1/shifts/sync returned code 400.
Truncated server response:
{"message": "Publishing requires either a date range or a list of
events"} (use muteHttpExceptions option to examine full response)
(line 256, file "Code")"
Sling API's "documentation" for the shift posting feature is available here: https://api.sling.is/#/shifts/post_shifts_sync
Any help would be greatly appreciated.
From the API document in your question, it seems that the request body is an object including an array. And it seems that the key is event. So could you please try this modified script? When you run this, please set notes and headers.
Modified script :
var payloadtwo = {
"event": [ // or "Event"
{
"summary": notes,
"dtstart": "2018-11-07T12:00:00:00.000-04",
"dtend": "2018-11-09T12:00:00:00.000-04",
}
]
};
var optionstwo = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payloadtwo),
'headers': headers,
'muteHttpExceptions': true,
};
var res = UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
Logger.log(res)
Note :
If the error occurs, please modify from 'payload': JSON.stringify(payloadtwo), to 'payload': payloadtwo, and run it again.
I couldn't try to test because I have no account. So if this script occurs the error, please tell me. I would like to think of other modification points.
Edit 1 :
Modified script :
var payloadtwo = [
{
"summary": notes,
"dtstart": "2018-11-07T12:00:00:00.000-04",
"dtend": "2018-11-09T12:00:00:00.000-04",
}
];
var optionstwo = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payloadtwo), // or payloadtwo
'headers': headers,
'muteHttpExceptions': true,
};
var res = UrlFetchApp.fetch("https://api.sling.is/v1/shifts/sync", optionstwo);
Logger.log(res)
I'm trying to POST to an API endpoint on my server. I know my endpoint works because if I use Advanced REST Client, I can hit it and get a JSON response as expected. The problem seems to be that no data is being sent in the body of my request despite calling request.write(postData) which contains a key, value pair. Without this data being sent in the body, my server returns a 401 error as expected without this information. Printing out the content of the POST server-side is empty but I'm clueless as to why it's empty.
var postData = querystring.stringify({
"access_token" : accessToken,
"id": applianceId
});
var serverError = function (e) {
log("Error", e.message);
context.fail(generateControlError(requestName, "DEPENDENT_SERVICE_UNAVAILABLE", "Unable to connect to server"));
};
var callback = function(response) {
var str = "";
response.on("data", function(chunk) {
str += chunk.toString("utf-8");
});
response.on("end", function() {
result = generateResult(CONTROL, requestName.replace("Request", "Confirmation"), messageId);
context.succeed(result);
});
response.on("error", serverError);
};
var options = {
hostname: REMOTE_CLOUD_HOSTNAME,
port: 443,
path: REMOTE_CLOUD_BASE_PATH + "/" + endpoint,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
};
var request = https.request(options, callback);
request.on("error", serverError);
//This doesn't seem to write anything since if I print out the POST
//data server-side it's empty; however, if I print out the value of
//postData here, it looks as expected: 'access_token=xxxxx'
request.write(postData);
request.end();
I have testing you code again httpbin.org/post and it seems that it is working.
I believe that the issue related to, that your should POST application/json and not "application/x-www-form-urlencoded
Please try to change the header
headers: {
"Content-Type": "application/json"
}
Then, try to change the postData to JSON string:
var postData=JSON.stringify({access_token:"xxxxx"})
To be sure that problem you success to send and the problem is not local (maybe there is an issue in your server), change the target to mirror URL:
var options = {
hostname: "httpbin.org",
path:'/post',
port: 443,
method: "POST",
headers: {
"Content-Type": "application/json"
}
};
If there is no problem in your NodeJS version, the is the response you should get: (It is mean that the server got the posted data)
{
"args": {},
"data": "{\"access_token\":\"xxxxx\"}",
"files": {},
"form": {},
"headers": {
"Content-Length": "24",
"Content-Type": "application/json",
"Host": "httpbin.org"
},
"json": {
"access_token": "xxxxx"
},
"origin": "5.29.63.30",
"url": "https://httpbin.org/post"
}
BTW: I really recommend you to move to a library to manage the request for you:
https://github.com/request/request - Very popular
https://github.com/request/request-promise - For popular who like to use the Promise syntax (The next thing in JavaScript)
https://github.com/visionmedia/superagent - For people who like to write same code in Browser & Server