Javascript fetch faild API call to servicedesk plus - javascript

I am trying to create a fetch call to servicedesk plus system but I keep getting 400 error, I understand that the request I made is not what the server wanted but in postman, I do manage to send that same query successfully. I can't understand what is the problem
In the dev tools network tab I see this data after dending the Json:
response_status: {status_code: 4000,…}
messages: [{status_code: 4001, field: "input_data", type: "failed", message: "JSON cant be analyzed"}]
0: {status_code: 4001, field: "input_data", type: "failed", message: "JSON cant be analyzed"}
field: "input_data"
message: "JSON cant be analyzed"
status_code: 4001
type: "failed"
status: "failed"
status_code: 4000
From what I read in the API documentation I saw that the 4001 error means that the ID or the name are not as they are in the service desk system.
here is a link to the API docs
this is my code:
const jss = {
"request": {
"subject": "test 29072020",
"description": "TEST REQUEST BY DAVID",
"requester": {
"id": "1231",
"name": "david"
},
"resolution": {
"content": "Mail Fetching Server problem has been fixed"
},
"status": {
"name": "פתוחה"
},
"template": {
"name": "Test for API",
"id": "123123"
},
}
}
const sendToSd = document.getElementById('send');
sendToSd.addEventListener('click', submitData);
var mydata = JSON.parse(jss);
var stringify = JSON.stringify(mydata);
async function submitData(){
const url = 'http://MYURL.COM/api/v3/requests?TECHNICIAN_KEY=SOME-STRING&input_data='+stringify+'&FORMAT=json';
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
console.log('response',response)
}
This fetch works and manages to retrieve the data from the service desk using the same URL and TECHNICIAN_KEY.
// fetch('http://MYURL.COM/api/v3/requests/61627?TECHNICIAN_KEY=SOME-STRING', {
// method: 'GET'
// })
// .then(response => {
// console.log(response);
// return response;
// });

Related

Checkout.com Payment response JavaScript

I am trying to integrate https://www.checkout.com/ in my app.
I tried there sample code to get token.
Frames.addEventHandler(
Frames.Events.CARD_TOKENIZED,
function (data) {
Frames.addCardToken(form, data.token);
if (data.token) {
confirmPayment(data.token);
} else {
console.log(data);
}
}
);
I tried https://api.sandbox.checkout.com/payments/ api to do the payments,
payment successfully captures, but I am unable to read its response to or redirect user on successfully attempt.
async function confirmPayment(token) {
// Storing response
const response = await fetch('https://api.sandbox.checkout.com/payments/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk_sbox_..abc'
},
body: JSON.stringify({
"source": {
"type": "token",
"token": token
},
"Capture": true,
"processing_channel_id": "pc_..abc",
'amount': 1000,
'currency': 'USD',
"3ds": {
"enabled": false
},
"customer": {
"email": "test.testUI#example.com",
"name": "John Test"
},
'reference': 'ORD-175-759',
"metadata": {
"udf1": "UI-CALL-TEST",
"coupon_code": "NY2018",
"partner_id": 123989
},
"success_url": "http://example.com/payments/success",
"failure_url": "http://example.com/payments/fail"
})
});
// Storing data in form of JSON
var data = await response.json();
console.log(data);
if (response) {
}
show(data);
}
I want to get a payment response like errors "card invalid" etc
Also redirect to Url if successful.
Please let me know if this is a correct way to do the payment or If there any JavaScript library that I can use?
I want to do payment on client side and use webhook later.
Thank you

ZenDesk API cannot POST array inside an object

I am using zafClient to perform requests as per this article:
https://developer.zendesk.com/apps/docs/core-api/client_api#client.requestoptions
So far I am successful with GET requests and can fetch the information needed. Example:
zafClient.request({
url: '/api/v2/macros.json',
httpCompleteResponse: true,
}).then(response => {
console.log(response.responseJSON);
}, error => {
console.log(error.responseText)
})
but, when I perform POST operation, I am getting nasty error that I cannot fight.
here is post:
zafClient.request({
url: '/api/v2/macros.json',
method: 'POST',
data: {
"macro": {
'title': "Created Macro with API test",
'actions': [{ "field": "subject", "value": "Change subjectline with API" }]
}
}
}).then(res => console.log(res), error => console.log(error.responseText))
And here is the error.responseTest
{
"error": {
"title": "Invalid attribute",
"message": "You passed an invalid value for the actions attribute. Invalid parameter: actions must be an array from api/v2/rules/macros/create"
}
}
Am I missing something in the post operation? if I log just the object "macro" I can see that attribute "actions" is an array, so the object "macro" is an exact object that I am fetching from API
Any ideas would be welcome as to what am I doing wrong.
Now I know that I was supposed to JSON.Stringify passing data :)
zafClient.request({
url: '/api/v2/macros.json',
httpCompleteResponse: true,
contentType: 'application/json',
method: 'POST',
data: JSON.stringify({
macro: {
title: "Created Macro with API test",
actions: [{ "field": "subject", "value": "Change subjectline with API" }]
}
})
}).then(res => console.log(res), error => console.log(error.responseText))
First experience with HTTP requests

Build cusom json for ajax rest request

Im trying to send a request to a rest API and granted my knowledge using jquery is not advance however through numerous tutorials I'm struggling a bit to build a request based on this swagger documentation.
{
"fields": {
"": [
{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
}
This is the model of how i need to send the Rest request, im able to do this using postman however i struggle to do this in javascript.
var data = {};
var json = [{ "NAME": "name", "ADDRESS": "address", "EMAIL": "email" }];
data.fields ={json};
My problem is that in the model there is an empty quotation which im unable to replicate. I suspect that either the rest API is not the best or im missing something quite vital in building a request. See below for the actual ajax jquery request.
var request = $.ajax({
type: "POST",
url: urlBase,
contentType: 'application/json',
data: JSON.stringify({json}),
});
request.done(function (msg) {
alert(msg);
$("#log").html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
Error message based on the above request
Invalid field groups: [json] used in the search fields not found in duplicate store schema
You can create a json like this:
var obj = {
"": [{
"NAME": "NAME"
},
{
"ADDRESS": "ADDRESS"
},
{
"EMAIL": "EMAIL"
}
]
}
console.log(obj)
Hope it helps. Revert for any doubts.

Send Mail with attachment Microsoft Graph not working

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"
})
}
...
}

Google Calendar REST API errors

I'm trying to implement a simple POST call in meteor.js to the Google Calendar API, and I'm stuck. My request looks like this:
var id = Meteor.http.post("https://www.googleapis.com/calendar/v3/calendars/", {
'headers' : {
'Authorization': auth, // auth = "Bearer " + Meteor.user().services.google.accessToken
'Content-Type': 'application/json'
},
'parameters': {},
'body' : {
'title': "Calendar Title",
}
});
and I get the following error:
Error: failed [400] {
"error": {
"errors": [{
"domain": "global",
"reason": "required",
"message": "Missing title."
}],
"code": 400,
"message": "Missing title."
}
}
Any ideas?
Solved it. This is dumb.
Take out parameters, and make "body" "data" instead and it works.

Categories