Error 400/401 trying to create a webhook - json

I am brand new to webhooks and have had a nightmare trying to get my first one to function. I am trying to use a Particle Photon to send a single float temperature variable to a site that can graph the data. I've tried creating webhooks to thingspeak.com and librato.com with no success. My main attempts have been trying to use the json code in tutorials to create the webhook.
Here is my Photon's code:
#include "Particle.h"
float temp = 70.1000;
float adjust = 0.4;
int acOn = 0;
void setup()
{
}
void loop()
{
if(temp < 72)
adjust = random(1620000)/1000000.0;
else if(temp < 74)
adjust = random(1000000)/1000000.0;
else
adjust = -1*random(500000,2200000)/1000000.0;
temp = temp + adjust;
Particle.publish("librato_", String(temp), 60, PRIVATE);
Particle.process();
delay(30000);
}
and the webhook JSON code (for the librato attempt)
{
"event": "librato_",
"url": "https://metrics-api.librato.com/v1/metrics",
"requestType": "POST",
"auth": {
"username": "YOUR_LIBRATO_USERNAME",
"password": "YOUR_LIBRATO_API_TOKEN"
},
"json": {
"gauges": [
{
"name": "{{NAME}}",
"value": "{{temp}}",
"source": "{{PARTICLE_DEVICE_ID (particle API token?)}}"
}
]
},
"mydevices": true
}
where I have filled in the username and API token found on librato and also the particle api token in the IDE settings. Thanks in advance for the help.

Looks like this user had a similar problem which was solved with a simple renaming or the webhook:
https://community.particle.io/t/connection-to-librato-solved/19230
Check with the Particle CLI if any events are being generated. If you are still not seeing data in Librato, reach out to support#librato.com so that we can check the API for errors.

Related

Best way to know which property has the error deserializing JSON?

I am currently getting invlaid JSON back from TFS similar to the following:
{
"value": [
{
"version": 46874,
"changeDate": "2016-10-27T11:18:37.14Z",
"size"/8,
"hashValue": "ADnOi7g3m13IlYXnt9Q5Qw==",
"path": "$/some/random/file",
"url": "https://example.com/blah"
}, //...
],
"count": 14
}
While the TFS admins figure out what is wrong with TFS, I've decided that the, while undesirable, not having the file's size is not crucial to the project and I want to just ignore this error for now.
Google lead me to this question. If I wanted to ignore all errors, this would be fine. I only want to ignore the error for the size property. So I wrote this error handler:
public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
{
if (errorArgs.ErrorContext.Path.EndsWith(".size"))
errorArgs.ErrorContext.Handled = true;
}
Unfortunately, errorArgs.ErrorContext.Path is value[2].changeDate when parsing the line "size"\8,. This seems wrong.
I could store the response in a field before deserialization and then use errorArgs.ErrorContext.Error.LinePosition like so:
public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
{
var pos = (errorArgs.ErrorContext.Error as JsonReaderException)?.LinePosition ?? 0;
if (pos > 6 && _parseData.Substring(pos - 6,6) == "\"size\"")
errorArgs.ErrorContext.Handled = true;
}
This seems awkward though. Does anyone have a better suggestion?

Google Apps Script and Big Query - tabledate.insertAll

Have been struggling with this..... Google Apps Script and the Big Query API are working well however when I try to use BigQuery.Tabledata.insertAll I keep getting an error saying 'no such field'.
When I try to run the same thing through the Google API explorer it works fine. The documentation says the command is :
BigQuery.TableData.insertAll(TableDataInsertAllRequest resource, String projectId, String datasetId, String tableId)
I have constructed the TableDataInsertAllRequest resource as per the documentation https://developers.google.com/bigquery/docs/reference/v2/tabledata/insertAll and it looks like this :
{
"kind": "bigquery#tableDataInsertAllRequest",
"rows":
[
{
"json":
{
"domain": "test",
"kind": "another test"
}
}
]
}
This matches my table schema.
When I run the command the error returned is :
{
"insertErrors": [
{
"index": 0,
"errors": [
{
"message": "no such field",
"reason": "invalid"
}
]
}
],
"kind": "bigquery#tableDataInsertAllResponse"
}
As I say the same TableDataInsertAllRequest resource works fine in the API explorer (clicking Try It on the documentation page above) it just does not work through Apps Script.
Any help gratefully received.
I've run into this too, and had somewhat better luck with this variation.
var rowObjects = [];
// Generally you'd do this next bit in a loop
var rowData = {};
rowData.domain = 'test';
rowData.kind = 'another test';
rowObjects.push(rowData);
// And at this point you'd have an array rowObjects with a bunch of objects
var response = BigQuery.Tabledata.insertAll({'rows': rowObjects}, projectId, datasetId, tableId);
Some things to note:
I don't indicate a kind -- it is implied by the call to insertAll()
I use dot notation (is that the right term?) rather than strings to stuff attributes into my "row objects"
I'm not sure which of these is the Secret Sauce. Anyways, in the end, the structure of the call looks about like this:
BigQuery.Tabledata.insertAll({'rows' : [
{
'domain' : 'test',
'kind' : 'another test'
}
]
},
projectId,
datasetId,
tableId);

HttpRequest.getString hitting error function even though its succeeding

Wondering if anyone here could help?
Using Polymer Dart I've set up a service to load a Json feed using the following code:
Future loadService(){
return HttpRequest.getString(_serviceURL)
.then(buildView)
.catchError(handleError);
}
When this code executed, it does successfully hit my buildView function, but I'm also getting an error printed out from my handle error function:
void handleError(Error error){
print(error);
}
I have 3 items in my json feed:
[
{
"module": "module-1",
"data": {
"title": "Dynamic Title 1",
"text": "This is the dynamic text for content block 1."
}
},
{
"module": "module-2",
"data": {
"title": "Dynamic Title 2",
"text": "This is the dynamic text for content block 2."
}
},
{
"module": "module-3",
"data": {
"title": "Dynamic Title 3",
"text": "This is the dynamic text for content block 3."
}
}
]
The error I'm getting is: "RangeError: 3".
I can't find a lot of information about what could be causing this. It doesn't seem to be hindering my app, but I would like to clear it up if at all possible. If anyone has any suggestions, I'm all ears.
Thanks!
Edit: as per the suggestion by Günter Zöchbauer
Now I understand the .catchError() function catches errors from the .then() function. I thought it was only going to catch errors around the HttpRequest itself failing.
In buildView I was looping through the json object using a for loop like this:
void buildView(String jsonString){
contentBlocks = JSON.decode(jsonString);
DivElement wrapper = $['content-modules-wrapper'];
for(int i=0; i < contentBlocks.length; i++){
Element element = new Element.tag(contentBlocks[i]['module']);
wrapper.children.add(element);
}
}
Which is wrong, because .length takes the JSON string length (300 something characters) which i think is a bit weird since I've converted it to an object.. anyway, i fixed it by changing the function to this:
void buildView(String jsonString){
contentBlocks = JSON.decode(jsonString);
DivElement wrapper = $['content-modules-wrapper'];
contentBlocks.forEach((block){
Element element = new Element.tag(block['module']);
wrapper.children.add(element);
});
}
Is there a way to get the number of items in a json object like I was trying to do or should you always just loop through it using forEach()?
This error is probably from your buildView. The indexes of the result are from 0 to 2 not from 1 to 3.

POST request with large body received empty on server side

When issuing a POST request with a large body to my Play framework action method, I get null when extracting the data. If the body is fairly small, I can retrieve the data just fine.
Here's a sample short data set:
{
"creator": "zoltan",
"sport": "hike",
"geometry": [
{
"time": "2009-07-10 12:56:10 +0000",
"x": 10.275514,
"y": 47.514749,
"z": 756.587
},
{
"time": "2009-07-10 12:56:19 +0000",
"x": 10.275563,
"y": 47.514797,
"z": 757.417
}
]
}
When I issue a POST request with this JSON in the body, everything works fine. However, if I add many more (~4000) points in the geometry array, I get null in the action.
Here's my action method:
#Transactional
//#BodyParser.Of(Json.class) // tried with this as well
public static Result createTour() {
LOG.debug("Raw request body: " + request().body().asText());
JsonNode node = request().body().asJson();
LOG.debug("JSON request body: " + node);
TourDto tourDto;
try {
tourDto = jsonToTour(node);
int id = TourDataAccessUtils.create(tourDto);
return created(toJson(id));
} catch (JsonProcessingException e) {
LOG.error("While parsing JSON request.", e);
return Results.badRequest(
toJson(Throwables.getRootCause(e).getMessage()));
}
}
I tried using both Advanced REST Client in chrome and ċurl to send the request, both failed.
What could be the problem? Could it be that I need to include a Content-Lenght header for large requests? If so, how can I manually calculate it for arbitrary JSON data?
Please check the PlayFramework documentation, They mentionned that the default maximum length for request is 100KB:
Max content length
Text based body parsers (such as text, json, xml or
formUrlEncoded) use a max content length because they have to load all
the content into memory.
There is a default content length (the default is 100KB).
Tip: The default content size can be defined in application.conf:
parsers.text.maxLength=128K
You can also specify a maximum content length via the #BodyParser.Of
annotation:
// Accept only 10KB of data.
#BodyParser.Of(value = BodyParser.Text.class, maxLength = 10 * 1024)
pulic static Result index() {
if(request().body().isMaxSizeExceeded()) {
return badRequest("Too much data!");
} else {
ok("Got body: " + request().body().asText());
}
}

Facebook Graph API not returning standard JSON

I am working on an iOS app using the MonoTouch framework. I am using Visual Studio 2010 Professional SP1 with the Xamarin.iOS (v1.3.250) extension. I have been able to open a valid FacebookConnect.FBSession by using the FacebookConnect.FBLoginView with no issues but when I try to make a Graph API request using FacebookConnect.FBRequest I recieve a non-standard JSON style string. When I run following request through the Graph API Explorer:
me?fields=albums.fields(id,name,cover_photo)
I receive the following response:
{
"id": "111111111111111111",
"albums": {
"data": [
{
"id": "111111111111111111",
"name": "Some Album (#1)",
"cover_photo": "111111111111111111",
"created_time": "000-00-00T00:00:00+0000"
},
{
"id": "111111111111111111",
"name": "Some Album (#2)",
"cover_photo": "111111111111111111",
"created_time": "000-00-00T00:00:00+0000"
},
],
"paging": {
"cursors": {
"after": "xxxxxxxx=",
"before": "xxxxxxxx="
}
}
}
}
Now all of this is just fine and is what I expect to receive but when I make the same Graph API request from my app like this:
public static void GetPhotoAlbums(string _userID)
{
// _userID = "me"
mFBRequest = new FBRequest(FBSession.ActiveSession, _userID + "?fields=albums.fields(id,name,cover_photo)");
FBRequestConnection fbRequestConnection = new FBRequestConnection();
fbRequestConnection.AddRequest(mFBRequest, OnPhotoAlbumsReceived);
fbRequestConnection.Start();
}
static void OnPhotoAlbumsReceived(FBRequestConnection _connection, NSObject _result, NSError _error)
{
if (_error == null)
{
Console.WriteLine("FacebookManager.OnPhotoAlbumsReceived() - JSON: " + _result.Description);
object o = JsonConvert.DeserializeObject(_result.Description);
// ...
}
}
I receive this JSON 'like' response:
{
albums = {
data = (
{
"cover_photo" = 111111111111111111;
"created_time" = "000-00-00T00:00:00+0000";
id = 111111111111111111;
name = "Some Album (#1)";
},
{
"cover_photo" = 111111111111111111;
"created_time" = "000-00-00T00:00:00+0000";
id = 111111111111111111;
name = "Some Album (#2)";
},
);
paging = {
cursors = {
after = "xxxxxxxx=";
before = "xxxxxxxx=";
};
};
};
"id": "111111111111111111";
}
I'm not really sure how/why I'm getting a response formatted in a non-standard way but needless to say, I get Newtonsoft.Json.JsonReaderException when attempting to deserialize the data because it does not follow the standard formatting rules (ie, = instead of : to separate key/value pairs, ; instead of , to separate elements of a container, some keys having quotes while others do not, etc...)
I'm pretty new to Facebook and JSON stuff in general and am really at a loss for what is happening to the response string I receive. Any help, feedback, ideas are greatly appreciated. Thanks.
* Solution *
After a bunch of digging around it seems to be that the Graph API response is indeed JSON but it gets converted to an FBGraphObject which holds a NSMutableArray as it the data makes its way through the MonoTouch->.NET bindings so when I pulled _result.Description (equivalent to _result.ToString() it returned me the string representation of that object which happens to look a lot like JSON but is not. After finding all this out (and a lot of runtime experimentation), I was finally able to extract the data into a usable state by doing this:
static void OnPhotoAlbumsReceived(FBRequestConnection _connection, NSObject _result, NSError _error)
{
if (_error == null)
{
NSArray fieldData = (NSArray) _result.ValueForKeyPath(new NSString("albums.data.name"))
string[] names = NSArray.StringArrayFromHandle(fieldData.Handle);
// ...
}
}
Although this works for me, I have a feeling that there is a better or more robust way to get the data I requested, so if any developers out there can offer any additional tips for improving this solution, I would love to hear them.
As stated in Facebook SDK documentation Graph API:
When a request returns a non-JSON response (such as a "true" literal),
that response will be wrapped into a dictionary using this const as
the key. This only applies for very few Graph API prior to v2.1.
So you can check first if result is an NSDictionary, otherwise you can deserialize the JSON data as usual.
Below some obj-c code you can translate into C#/MonoTouch (I don't know the framework, I hope it is helpful).
NSDictionary *dict;
if ([graphResult isKindOfClass:[NSDictionary class]]) {
dict = (NSDictionary *)graphResult;
} else {
NSError *JSONError;
dict = [NSJSONSerialization JSONObjectWithData:graphResult options:NSJSONReadingAllowFragments error:&JSONError];
if (JSONError) {
NSLog(#"Facebook: JSON parse error: %#", JSONError);
// Handle error
}
}