How to query parse.com REST API from angularjs - angularjs

I have a working curl call:
curl -X GET \
-H "X-Parse-Application-Id: XXXX" \
-H "X-Parse-REST-API-Key: YYYY" \
-G \
--data 'where={"number":1}' \
https://api.parse.com/1/classes/Day
How do I translate this into an angular $http call? I have tried every permutation I can think of, and it still retrieves every Day object. Base on the documentation, I expected the following to work:
$http({method: 'GET', url: 'https://api.parse.com/1/classes/Day',
data: {"where": {"number": 1}}});
EDIT:
I updated my code to use the Parse JavaScript SDK as recommended in the accepted solution. I installed it using bower:
bower install --save parse
In my app.js I initialize Parse:
Parse.initialize(parseAppId, parseJavascriptKey);
The controller code is a lot more verbose than what I had before, but does work correctly and provides more flexible querying:
var Day = Parse.Object.extend("Day");
var query = new Parse.Query(Day);
query.equalTo("number", currentDay); // Only retrieve objects matching currentDay
query.include('challenge,quote'); // Related objects
query.find({
success: function(results) {
console.log("Retrieved object with id: " + results[0].get('id'));
$scope.day = results[0];
$scope.$apply();
},
error: function(error) {
console.log(err);
}
});

While Wayne is 100% correct, We have decided to go a bit further and wrote a parse-angular seed project for developing web apps. It can be found here.
After you pulled it, do a npm install
As usual, cloud code should go into cloud/main.js,
express code: cloud/app.js
angular code: cloud/public/js/
Note that: You will need to change your AppId and AppKey in
config/global.json
cloud/public/js/app.js
Then you should have a nice parse-angular project set up and good to go.
If there's anything wrong, please feel free to open a pull request. :)

Instead of using $http you should be using the parse javascript api instead. https://parse.com/docs/js/guide

Related

BOX API by Google Apps Script - new file version upload

I've already asked the GAS community but I was advised to continue asking here...
So far I'm able to connect to BOX and get a list of files and I can download a file from BOX as well.
The whole idea is to download a file using BOX API, edit it and upload it back as a new file version using the BOX API.
I'm unable to make the last part working as it gives me error code 400.
Here is the function.
function uploadNewFileVersion() {
//767694355309 testing
var boxFileId="767694355309";
var newVerFile = DriveApp.getFileById("1sK-jcaJoD0WaAcixKtlHA85pf6t8M61v").getBlob();
var confirmAuthorization = getBoxService_().getAccessToken();
//var parent = { "id": "0" };
//"name": "apiNewVersion.xlsx",
//"parent": parent,
var payload = {
"file": newVerFile
}
var headers = {
'Authorization': 'Bearer ' + confirmAuthorization
}
var options = {
"method": "post",
"muteHttpExceptions": true,
"contentType": "multipart/form-data",
"headers": headers,
"payload": payload
}
var apiHtml = "https://upload.box.com/api/2.0/files/"+boxFileId+"/content/";
var response = UrlFetchApp.fetch(apiHtml, options);
Logger.log(response.getResponseCode());
var a = 1;
}
The boxFileId is the file on the box.
The newVerFile is the one downloaded from Box and updated. I need to make it as a new version of the Box file.
Could you please advise?
Thank you!
PEtr
I think parent and name is optional so I commented it out.
If I don't getBlob, then it returns 415 istead.
I believe your goal and situation as follows.
You want to upload a file of Google Drive using Box API with Google Apps Script.
From your question, I cannot find the official document of the method of API that you want to use. But, from the endpoint https://upload.box.com/api/2.0/files/"+boxFileId+"/content/ in your script, I guessed that you wanted to use "Upload file version".
Values of your access token and file ID are valid for using the API.
If my understanding of your question is correct, how about the following modification?
Modification points:
When I saw the official document of "Upload file version", I confirmed the following sample curl. In this case, it is considered that when the following curl command is converted to Google Apps Script, the request might work.
$ curl -i -X POST "https://upload.box.com/api/2.0/files/12345/content" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: multipart/form-data" \
-F attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" \
-F file=#<FILE_NAME>
From the curl command, it is found that attributes and file are sent as form and files.
And, I thought that attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" might should be attributes="{\"name\":\"Contract.pdf\", \"parent\":{\"id\":\"11446498\"}}".
When I saw your current script, it seems that multipart/form-data is used for contentType. In this case, boundary in the request body is required to be included. Fortunately, at UrlFetchApp, in the case of multipart/form-data, when contentType is not used, the content type is automatically included in the request header. I think that in your case, this can be used.
In your script, attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" is not included. But I thought that you might use it in the future script. So in this answer, this is also included.
When above points are reflected and the sample curl command on the official document is converted to Google Apps Script, the script becomes as follows.
Sample script:
Please copy and paste the following script to the script editor and set the variables, and run the function of myFunction. By this, the request same with the sample curl is requested with Google Apps Script.
function myFunction() {
const accessToken = "###"; // Please set your access token.
const fileId = "###"; // Please set your fileId.
const fileBlob = DriveApp.getFileById("1sK-jcaJoD0WaAcixKtlHA85pf6t8M61v").getBlob();
const metadata = {name: "Contract.pdf", parent: {id: "11446498"}}; // Please set your file metadata.
const params = {
method: "post",
headers: {Authorization: `Bearer ${accessToken}`},
payload: {
attributes: JSON.stringify(metadata),
file: fileBlob,
},
muteHttpExceptions: true,
};
const url = `https://upload.box.com/api/2.0/files/${fileId}/content`;
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText());
}
I could confirm that above sample script is the same request with above sample curl.
If you don't want to use the file metadata, please remove the line of attributes: JSON.stringify(metadata), from payload.
Note:
In this case, the maximum data size ("URL Fetch POST size") of UrlFetchApp is 50 MB. Please be careful this. Ref
About the limitation of file upload of Box API, please check https://developer.box.com/guides/uploads/.
If your access token and file ID are invalid, I think that an error occurs. So please be careful this.
References:
Upload file version
Class UrlFetchApp

Trouble accessing remote JSON in AngularJS

So, I have been working on this exercise and I'm down to one final problem.
The JSON is on a different server. If I use a plain old $http.get then it doesn't allow the cross-server request. When I switch and use $http.jsonp I get to the file but it claims an unexpected ":" right away. I've validated their JSON so I'm not sure what's going on.
This is the current implementation of the call:
app.factory('users', ['$http', function($http) {
return {
callExternalJson: function() {
return $http.jsonp('http://applicant.pointsource.us/api/testUser/577ebf34f62a2d8f3c05d9c0?callback=JSON_CALLBACK').then( function(response) {
return response;
});
}
}
}]);
How do I get that remote JSON file?
Something to note: that remote JSON changes every time you hit it.
I also tried a different way of using jsonp that I've used in the past to access other RESTful APIs and got the same result of it choking on their first colon.
The problem isn't your code, but instead the server.
Try replacing the URL with this Test URL that supports JSONP. http://ip.jsontest.com/?callback=JSON_CALLBACK

How To Call XML Service With AngularJS

I know that AngularJS prefers JSON, but I can't get my Web API to work with JSON. I've tried for 3 days and I'm not going to try anymore. I can get it to return XML. Can I retrieve the XML data with AngularJS? I have written the $http call below and it always fails with no status text. I've tried asking for XML type and I've tried the default call. You can see that all 3 of these URLs return XML data in the browser:
http://stevegaines.info/api/Exams?id=3&extra=0
http://stevegaines.info/api/Exams/4
http://stevegaines.info/api/values
$http.get(url)
.then(function (dataResponse)
{
$scope.Exams = dataResponse.data;
}, function (error)
{
alert("error.statusText = " + error.statusText);
});
I've just tried to call your api with $http service and it works ok. I think you should start investigating this problem with looking at network tab in chrome developer tools when making such a request.

No response Data Angularjs POST / TypeScript

I'm trying to test AngularJS's post method out, but so far I have not figured out how to get it work.
Here is my code snippet.
parameter = { categoryName: '' }; <- just a dummy parameter purposely set to '' for testing purposes
this.httpService({
method: 'POST',
url: '/svc_templates/svc_fetch_category.php',<- Just echoing some JSON string.
data: parameter
}).then(function (response) {
console.log(response);
The response I'm getting is shown below.
It seems that a call to the php file is going through, but the actual data(JSON) is not returning for some reason...
Could anyone help me out?
Make sure that the server .php file is actually working using curl e.g.:
curl -X POST -d #filename.txt http://example.com/svc_templates/svc_fetch_category.php --header "Content-Type:application/json"
Where filename.txt contains the JSON data you want to send.

Parse.com RESTAPI&angularJS query constraints key issue

I have a function which does a HTTP GET request on Parse, using the code below. (I'm using AngularJs).
$http({ method: 'GET',
url: 'https://api.parse.com/1/classes/foo',
headers:{
"X-Parse-Application-Id": "MYPARSEAPPID",
"X-Parse-REST-API-Key": "MYPARSERESTAPIKEY",
"X-Parse-Session-Token": UserService.sessionToken,
},
params: {
where:{"toto":{"$gt":42}}
}
}).success(function(data, status) {
/* DO SOMETHING*/
}).error(function(data, status) {
/* DO SOMETHING */
});
I wrote this code using Parse' REST documentation (https://www.parse.com/docs/rest#queries-constraints)
which give this example (curl):
curl -X GET \
-H "X-Parse-Application-Id:..............." \
-H "X-Parse-REST-API-Key:.............." \
-G \
--data-urlencode 'where={"score":{"$gte":1000,"$lte":3000}}' \
https://api.parse.com/1/classes/GameScore
This is the result of the AngularJS request above seen through Chrome's Dev Tools:
where:{"toto":{}}
And this this the result of the same code, without the '$' character (it doesn't work, but the requet is sent as it should):
where:{"toto":{"gt":42}}
As you can see, the constraint disappears because of the '$' character.
I supposed angular doesn't let us use '$' as it is used for Angular properties/methods.
Any suggestion/ideas/example will be very helpful.
Edited:
I tried to stringify the params as RobH said, click here to look at the result seen through Chrome's Dev Tools.
The result of this query seems ignore completly the given contraints, even if the '$' caracter hasn't been striped. I found that someone else tried to stringify the params (How to pass parameters to $http in angularjs?), but according to the last comment, it "does not work ({method:'GET', url:'/search', stringifiedJsonData} is not a valid JavaScript literal)". I'm not sure about the relevance of this comment as I'm new at AngularJs and web in general.
Any other ideas ?

Resources