POST projects in Toggl through API - javascript

I'm developing an API to integrate the Knack with Toggl. So, I need to post some data in the Toggl using an API that will be running in Google Script (JavaScript).
When I try to post somes projects in the Toggl, I receive the following error: "Request failed for https://www.toggl.com/api/v8/projects returned code 400. Truncated server response: Project can't be blank (use muteHttpExceptions option to examine full response) (line 61, file "")"
My source code is:
function sendDataToToggl(){
var apiToken = '936e292eaccd99b40358edea25452880';
var unamepass = apiToken + ":api_token";
var digest = Utilities.base64Encode(unamepass);
var digestfull = "Basic " + digest;
var url = "https://www.toggl.com/api/v8/projects";
var data = {"project":{"name":"An awesome project","wid":1034130,"template_id":1793088,"is_private":true,"cid":123397}};
var options = {
"Content-Type": "application/json",
"method": "post",
"headers": {"Authorization": digestfull},
"payload": data
//"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(url, options);
}

Change options:
Content-Type to contentType - https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
"payload": data to "payload": JSON.stringify(data) - will generate JSON string as payload.
Also, as you publicly posted your API key, you might want to get a new one.

Related

blank gravity form entries with API

I'm trying to create an entry in a Gravity form via API post in Google Apps script.
An entry gets created but the values are showing blank. any insight of where I'm possibly going wrong would be appreciated.
Below is my code:
function gravityForms(){
const url = 'https://example.com/wp-json/gf/v2/forms/18/entries';
const payload = [{"2":"My name"}];
const options = {
"method" : "post",
"payload" : JSON.stringify(payload),
"muteHttpExceptions" : true
};
options.headers = {
"Content-Type" : "application/json",
"Authorization" : "Basic " + Utilities.base64Encode("ck_xxxxxxxxxxxx:cs_xxxxxxxxxxxxxxxxxx")
};
const res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
}
This is the response I get back in the logger
{"0":{"2":"My name"},"form_id":18,"id":3320}
I removed the [] from the entry object and it worked. funny since the examples show to add them.

Google Apps Script GraphQL API Call

I've been working with the Canvas REST API and ran into some limitations and was directed to their experimental GraphQL API. Given its experimental nature, they have little to no documentation on it. Despite its advantages for what I'm building, I can't find a whole lot on the internet either. As of right now, I can't even get a basic query to work.
function testsendgraphql() {
const url = "https://hsccsd.beta.instructure.com:443/api/graphql";
const payload = `
query {
course(id: 1234) {
{
name
}
}
}`;
const options = {
"method": "POST",
"headers": { "Content-Type": "application/json", "Authorization": "Bearer "+getcanvasaccesstoken() },
"body": payload
};
Logger.log(query);
apiresponse = UrlFetchApp.fetch(url,options);
var head = apiresponse.getAllHeaders();
var data = JSON.parse(apiresponse.getContentText());
Logger.log(data);
Logger.log(head);
}
Running the above gets a response code of 200 but gives the following message:
{errors=[{message=No query string was present}]}
Something with my formatting of the payload seems to be off. Any help would be greatly appreciated.
I recently had success with the following GraphQL query using Google Apps Script:
function test(query) {
var url = "https://gql.waveapps.com/graphql/public";
var options = {"headers": {"Authorization": "Bearer " + getAccessToken(),
"Content-Type": "application/json"
},
"payload": JSON.stringify({query}),
"method": "POST"
}
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
return;
}
where the query that was passed into the function was formatted as follows:
var query = "query { user { id defaultEmail } }";
You must JSON.stringify your query and post it as payload.
I had a similar error to yours, that there was no query string present. It may be because GraphQL is looking in the URL arguments for the query, not in the HTTP request payload.
For example, get rid of the payload and change your URL to:
var url = encodeURI("https://gql.waveapps.com/graphql/public?query=query{course(id:1234){{name}}}");
Or maybe
var url = encodeURI("https://gql.waveapps.com/graphql/public?query={course(id:1234){{name}}}");
This was brought to my attention by this answer.

Rename video with Vimeo API

I'm looking to rename my videos with the Vimeo Api and Google Apps Script. I succesfully have the API moving videos into folders (using pretty much identical syntax to below) but can't for the life of me get the renaming working. It's extremely frustrating.
Here is the reference and below is my code - it just returns the video info as if I'm not trying to change anything, even though I'm clearly using a 'PATCH' call, not a 'GET'.
Where am I meant to put the 'name' parameter??
function renameVideo(){
var newName = 'thisismynewname';
var url = 'https://api.vimeo.com/videos/_________?name=' + newName;
var options = {
'method': 'PATCH',
'muteHttpExceptions': true,
'contentType': 'application/json',
'headers': {
'Accept':'application/vnd.vimeo.*+json;version=3.4',
'Authorization': "Bearer " + token,
},
//Note that I've also tried 'name' : 'thisismynewname' here too
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(JSON.parse(response).name); //it just returns the *current* name not the new one, and doesn't change it
}
When I saw the official document of Edit a video, it seems that name is included in the request body. So how about this modification?
Modified script:
function renameVideo(){
var newName = 'thisismynewname';
var url = 'https://api.vimeo.com/videos/_________'; // Modified
var options = {
'method': 'PATCH',
'muteHttpExceptions': true,
'contentType': 'application/json',
'headers': {
'Accept':'application/vnd.vimeo.*+json;version=3.4',
'Authorization': "Bearer " + token,
},
'payload': JSON.stringify({name: newName}) // Added
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(JSON.parse(response).name);
}
The content type is application/json.
Reference:
Edit a video

I'm sending a json object via the post method to my sendy database. It seems to work fine on desktop but does not send on mobile

I'm sending the json object userInfoRedCourses to my sendy database via the post method. This json object is sent from the previous page contains user details like email, name, address etc..If the user ticks the box the data is sent. I'm also changing some of the values in the object before the data is sent.
This works fine on desktop, but doesn't work at all on mobile. Please can anyone explain why?
I thought it might be a CORS error, but when I added dataType: 'jsonp',I stopped getting the CORS error, however the data is still not sent when using a mobile device. I see no other errors.
var userInfoRedCourses = <%- JSON.stringify(userInfo) %>;
var redCourseTickYes = document.getElementById("redcoursetickyes");
var redLicence = $("#Redlicence").val();
var drivingBan = $("#drivingBan").val();
var penPoints = $("#penaltyPoints").val();
userInfoRedCourses.redcoursetickyes = $("#redcoursetickyes").val();
userInfoRedCourses.Redlicence = redLicence;
userInfoRedCourses.DrivingBan = drivingBan;
userInfoRedCourses.penaltyPoints = penPoints;
if(redCourseTickYes.checked){
var redCourses = {
method: "POST",
"data": userInfoRedCourses,
crossDomain: true,
url: "https://example.com/sendy/subscribe",
dataType: 'jsonp',
"headers": {
"Host": "example.com",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
}
};
$.ajax(redCourses).done(function (response) {
console.log(JSON.stringify(response));
});
}

Sending files from client (angular) to server Asp.net wed api, request always has empty prorerty "files"

everyone, have a trouble with sending files
I have angularjs client:
var fd = new FormData();
var myEl = angular.element( document.querySelector( '#someId' ) );
fd.append('file', myEl[0].files[0]);
fd.append('test', 'value');
var vv = $resource('api/:domen/:url', { url: "", domen: 'Options' }, {
'saveF': {
headers: {
'Authorization': 'Bearer ' + currentUser.getProfile().token,
'Content-Type': false
},
method: 'POST'
}
});
vv.saveF({ url: "UploadData", domen: 'Info' }, fd, function (el) {
console.log(el);
});
The client code send fields, I can check it via Fiddler, the file is in body
and backend code on ASP.NET Web Api:
public async Task<IHttpActionResult> UploadData()
{
// var a = HttpContext.Current.Request;
// var f = a.Files.Get(0);
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.Contents)
{
var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
var buffer = await file.ReadAsByteArrayAsync();
and so on
The request always fails, because of "Request.Content.IsMimeMultipartContent()" or var f = a.Files.Get(0);
and I cannot get the file, server never see a content in request, but can see content-length
Already try to white content type 'multipart/form-data' but id didn`t help
Please, if somebody knows how to fix it - answer
See back-end implementation of Web API 2: https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-2
Also, you can use ng-file-upload for AngularJS
And example: https://github.com/stewartm83/angular-fileupload-sample
If you upload unknown MIME type and host your application on IIS,
it would be good add MIME type to IIS.

Categories

Resources