Make requests to third-party api from Parse.com - parse-platform

I need to do some requests every x period of time to YouTube v3 Api and then process this data and store it in Parse.com database.
Can i do this with Cloud Code (Jobs) ?

Yes, you can do this with the Parse.Cloud.httpRequest method (documentation).
Here is an example from the Parse documentation. This itself is failry simple but the mentioned documentation has more info about how to set parameters, request headers etc.
Parse.Cloud.httpRequest({
url: 'http://www.parse.com/'
}).then(function(httpResponse) {
// success
console.log(httpResponse.text);
},function(httpResponse) {
// error
console.error('Request failed with response code ' + httpResponse.status);
});

Related

Capture raw axios request from AWS Lambda

I have code that calls a vendor API to do a formdata upload of a file by axios from inside an AWS Lambda. The call returns a 400 error. If I run the code locally using the same node version v14 it works. I want to capture both raw requests and compare them for differences. How do I capture both raw requests? I've tried using ngrok and pipedream but they don't show the raw but decode the request and the file.
let response = null;
try {
const newFile = fs.createReadStream(doc);
const formData = new FormData();
formData.append("file", newFile);
formData.append("url", url);
const headers = {
Authorization: "Bearer " + token,
...formData.getHeaders(),
};
console.log("Headers: ", headers);
response = await axios.post(`${APIBASE}/file/FileUpload`, formData, {
headers,
});
console.log("file upload response", response);
} catch (err) {
console.log("fileupload error at API", err);
}
You might be able to just use a custom request interceptor and interrogate at the requests that way.
https://axios-http.com/docs/interceptors
You're not able to capture the request on the network level, as this is totally controlled by AWS. Maybe there's a way to do this when running in a VPC, but I don't think so.
You could simply use a tool such as axios debug logger to print out all of the request and response contents (including headers etc) before the request is made/after the response has arrived. This might provide some more information as to where things are going wrong.
As to the cause of the problem, it is difficult to help you there since you haven't shared the error message nor do we know anything about the API you're trying to call.
There are multiple ways to debug
axios debug logger .
AWS cloud watch where you can see all the logs. you can capture the request
and response.
Use postman to call the prod lambda endpoint and verify the response.

Using the Rally API to change the rank of an item

I am trying to use the Rally web service API to reorder 2 items.
From looking at the documentation i should be able to do:
$.ajax({
url: https://rally1.rallydev.com/slm/webservice/v2.0/task/12345?rankAbove=/slm/webservice/v2.0/task/56789,
type: 'PUT',
headers: { Authorization: Basic mytoken },
success: function(data) {
//do something
}
});
but i'm getting an error:
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '￿' [ chars read = \u003E\u003E\u003E￿\u003C\u003C\u003C ]"
The documentation doesn't seem to reveal what I could be doing wrong.
Cheers for your help
You won't be able to use basic auth to do this because there is an additional CSRF token you need to pass. I think you can make it work with an api key though:
headers: { zsessionid: myToken }
You didn't have any issues with reading data because the CSRF protection only kicks in when attempting to modify data.
For what it's worth, the App SDK generally handles most of this complexity for you. It looks like you're using jquery in your app here instead, which is why you need to do this low level stuff...

Can Mandrill be asked to dry-run sending of an e-mail? (Parse Cloud Code)

I'm using a Parse Cloud Job to send e-mails to all our ~1000 of users with Mandrill right now. Currently, I use a Parse.Cloud.httpRequest like so:
function sendNewsletterWithMandrill(info) {
var mandrillBody = computeMandrillBodyFromInfo(info); // takes a while per user
return Parse.Cloud.httpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
url: 'https://mandrillapp.com/api/1.0/messages/send-template.json',
body: mandrillRequestBody
});
};
I want test that this implementation runs within the 15 minutes for wall-clock time limit that Parse Cloud Jobs have.
i.e. I want my code to take the time to compute the e-mail body, and actually perform the request, but NOT actually send the e-mail.
How can I achieve this? Cheers.
You can create in Mandrill a test api key, it will make the request and give you a positive answer if the email was ok but it will not send the email.

The twilio module in Parse Cloud is missing latest APIs

Based on the API documentation on twilio.com, twilio.availablePhoneNumbers('COUNTRY_CODE').mobile.get() should exist. I should be able to call something like this below:
twilio.availablePhoneNumbers('US').mobile.get({
smsEnabled: true
}).then(function(searchResults) {
....
});
But when I used twilio module provided inside Parse cloud code, twilio.availablePhoneNumbers('COUNTRY_CODE').local and twilio.availablePhoneNumbers('COUNTRY_CODE').tollFree are available.
Am I wrong?
I need to programmatically acquire a phone number in the cloud code. If twilio on Parse cloud code is limited, how can I use the latest twilio APIs?
Twilio developer evangelist here.
The Twilio module on Parse is indeed outdated. I am currently working with their team to get an updated version available for developers like yourself.
In the meantime, you could use a normal HTTP request on Parse without the Twilio module to make calls like the one you are after. Something like this might work for now:
var accountSid = 'AC123...'; // your account SID
var authToken = 'xyzabc...'; // your auth token
var countryCode = 'US'; // the country code you want to search within
var url = 'https://';
url += accountSid + ':' + authToken + '#'; // add auth to URL
url += 'api.twilio.com/2010-04-01/Accounts/';
url += accountSid;
url += '/AvailablePhoneNumbers/';
url += countryCode;
url += '/Mobile.json';
Parse.Cloud.httpRequest({
url: url,
}).then(function(httpResponse) {
// success
console.log(httpResponse.text);
// httpResponse.data is the parsed JSON response
},function(httpResponse) {
// error
console.error('Request failed with response code ' + httpResponse.status);
});
You might want to check out the documentation for Parse's Parse.Cloud.httpRequest. It's available here: https://parse.com/docs/cloudcode/guide#cloud-code-advanced

Making jQuery $.ajax call to Twitter API 1.1 search

Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`

Resources