Appsync Resolver ResponseMappingTemplate- Direct mapping vs Template mapping - aws-appsync

I have the following ResponseMappingTemplate in AWS::AppSync::Resolver which does NOT work (following the doc from aws https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-http-resolvers.html )
ResponseMappingTemplate: |
{
#if($ctx.result.statusCode == 200)
$ctx.result.body
#else
$utils.appendError($ctx.result.body, "$ctx.result.statusCode")
#end
}
The above giving me error:
"message": "Unable to convert {\n
[{\"employeeId\":10901},{\"employeeId\":11352}]\n } to class
java.lang.Object."
However it works ok for direct mapping like so:
ResponseMappingTemplate: $ctx.result.body
i really don't understand, any ideas ?

The JSON blurb you posted doesn't seem to be valid.
{\n
[{\"employeeId\":10901},{\"employeeId\":11352}]\n }
there seem to be an extra {} around your list. A JSON object must have keys defined.

Related

HttpClient append parameter object to GET request

I'm quite the noob using Ionic or Angular for that matter. So as a cheat sheet I'm using the ionic-super-starter template (link below).
I am trying to make a get request to my API and it works just find if I'm doing it like this:
this.api.get('user/'+this.user.userId+'/entries?include=stuff&access_token=TOKEN');
but when I put the url params into an object it stops working:
let options = {
'include':'stuff',
'access_token':'TOKEN'
}
this.api.get('user/'+this.user.userId+'/entries', options);
The only error I get is "Unauthorized Request" since the options object including the access token was not appended to the url.
In the ionic-super-starter template the providers/api/api.ts calls .set() for each key in my params object:
if (params) {
reqOpts.params = new HttpParams();
for (let k in params) {
reqOpts.params.set(k, params[k]);
}
}
but according to Angular University this is not possible since "HTTPParams is immutable".
If it really was wrong to do this, I don't believe it would be in the ionic template. Nor would I believe that I would be the first person to come across this issue.
However, I am stuck here so any help would be appreciated.
Link to Angular University:
https://blog.angular-university.io/angular-http/#httprequestparameters
Link to ionic-super-starter:
https://github.com/ionic-team/starters/tree/master/ionic-angular/official/super
I think I figured it out myself:
if I write (in my src/providers/api/api.ts)
reqOpts.params = reqOpts.params.append(k, params[k]);
instead of
reqOpts.params.set(k, params[k]);
it works.
if you are using a loopback API as I am you might have nested objects like:
let options = {
"filter": {
"order": "date DESC"
},
"access_token":this.user._accessToken
};
this won’t work. try instead:
let options = {
"filter": '{"order":"date DESC"}',
"access_token":this.user._accessToken
};

LOOPBACK REST API for 'LIKE'

how can i type the REST API for "LIKE" Query on LoopBack ?
according to Loopback Documentation,
i already try like this :
ProductDealers?filter={"where":{"DealerCode":"T001","Active":"true","SKU":{"like":"1000.*"}}}
but it nothing happens,
please help me?
It would be something like
Post.find({
where: {
title: {
like: 'someth.*',
options: 'i'
}
}
});
and for api calls
?filter={"where":{"title":{"like":"someth.*","options":"i"}}}
Please take a look at this PR for more info
i found the answer , i didn't know why its can't work when i used brackets " {} "
but when i used " [] " , it works very well, like
Products?filter[where][Name][like]=%25" + valFilter + "%25&filter[where][Active]=1&filter[where][Deleted]=0"
Cheers!
A bit late but i actually found this after looking for something else.
The problem for most people is, that there is something called Url Encoding.
Read more here:
https://en.wikipedia.org/wiki/Percent-encoding
So if you stringify your json filter like in the examples above, make sure you put the stringified object into an Uri Encoder which will make sure you will get what you expect and will control the encoding of your values
let t_filter = {
where: {
title: {
like: 'someth.*',
options: 'i'
}
}
};
let result = encodeURI(JSON.stringify(t_filter));
After that send the result to your Api and not only the stringified Object

Creating Job from REST API returns a request property name error

I have my Asset and MediaProcessor ready. Now I am trying to encode my asset. When I send the request specified in the tutorial (http://msdn.microsoft.com/en-us/library/jj129574.aspx):
{
"Name":"CurlTestJob",
"InputMediaAssets":[
{
"__metadata":{
"uri":"https://wamsbluclus001rest-hs.cloudapp.net/api/Assets('nb%3Acid%3AUUID%3A429967f5-4709-4377-bab2-4680ae2a0dd87')"
}
}
],
"Tasks":[
{
"Configuration":"H.264 HD 720p VBR",
"MediaProcessorId":"nb%3Ampid%3AUUID%3A2e7aa8f3-4961-4e0c-b4db-0e0439e524f5",
"TaskBody":"<?xml version=\"1.0\" encoding=\"utf-8\"?><taskBody><inputAsset>JobInputAsset(0)</inputAsset><outputAsset>JobOutputAsset(0)</outputAsset></taskBody>"
}
]
}
I get the following response
{
"odata.error":
{
code: "";
message:
{
lang: "en-US";
value: "Parsing request content failed due to: Make sure to only use property names that are defined by the type";
};
};
}
I am using api-version 2.2
Can someone explain to me where am I wrong?
Try setting the Header "DataServiceVersion: 2.0"
I ran into the same issue when using "DataServiceVersion: 3.0"
The error says that properties in json file does not match the properties in the deserialized type.
http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.mediaservices.client.iasset.aspx shows that IAsset has property Uri, but say nothing about __metadata. You could try to change your json to
"InputMediaAssets":[{
"Uri":"https://wamsbluclus001rest-hs.cloudapp.net/api/Assets('nb%3Acid%3AUUID%3A429967f5-4709-4377-bab2-4680ae2a0dd87')"
}],

How to view TCL REST Response headers

My code sample was
package require rest
set yweather(forecast) {
url http://weather.yahooapis.com/forecastrss
req_args { p: }
opt_args { u: }
}
rest::create_interface yweather
Output
% set res [yweather::forecast -p 94089]
channel {title {content {Yahoo! Weather - Sunnyvale, CA}} .........
But i am trying to view Response header, like Status codes, set-cookie information. I don't know how to view, some one please help to resolve this issue.
Thanks
Typically with handling REST, I'd just use the standard http package directly (or wrapped into a little class). That would let you use http::meta to get at the gory response details, and also let you control much more precisely what message gets sent in the first place (usually rather important!)
However, that's me (as I'm pretty au fait with REST and the http package). Let's dig into the rest package more carefully and get it to do what we want.
By close reading of the documentation, I see that the interface descriptor dictionary allows the keys pre_transform and post_transform, and that the http token is available in the calling context. Let's try with the post_transform…
package require rest
set yweather(forecast) {
url http://weather.yahooapis.com/forecastrss
req_args { p: }
opt_args { u: }
post_transform extract_metadata
}
rest::create_interface yweather
proc extract_metadata {response} {
upvar 1 token token
lappend response [http::meta $token]
return $response
}
Now, if you do:
set res [yweather::forecast -p 94089]
You should get the extra information you want (and far more probably!) in the meta field at the end.

Accessing data from response of FB.api()

I am having difficulty accessing the returned JSON response data from the new Facebook JS SDK new Graph API calls.
For instance, in some of their docs where they are using the old way of using the SDK , they get a pointer to the data by response[0]
but here, it's showing that you need to use response.data[0] instead: http://developers.facebook.com/tools/console/ (click on fb.api — photo-albums)
So which is it? I know that with my code below, if I try using response[0] type of syntax to get at the returned JSON I get undefined.
If I use response[0].length I also get undefined
But if I try response.data[0].length I get 2 which I guess is the returned JSON or my 2 albums..I just don't know how to play with this returned object in terms of syntax and manipulating it, its properties, etc.
I want to in the end parse out the returned JSON using the jQuery parseJSON method but have no clue how to even pass the right syntax here for the response and just use that response object.
FB.api(uri, function(response)
{
alert("response: " + response);
// check for a valid response
if (response == "undefined" || response == null || !response || response.error)
{
alert("error occured");
return;
}
alert("response length: " + response.data.length);
}
this alert gave me 2 which makes sense. I have 2 albums.
then I tried something like response.data[0] and tried a jQuery parseJSON(response.data) or parseJSON(response.data[0]) on that and it does not work. So can someone explain the response object here as in regards to Facebook I guess? I see no docs about how to use that returned object at all and how it's constructed.
UPDATED:
Ok, so here's the entire parsing method attempt that I've stubbed out so far. I don't know if the jQuery parsing is 100% good code yet, I sort of stubbed that out but I can't even test that until I figure out how to use this response object coming back. I know it is returning JSON because I parsed another facebook response object in another method in the JS SDK so pretty sure that response[0] or response.data[0] will give you the JSON string.
function GetAllFacebookAlbums(userID, accessToken)
{
alert("inside GetAllFacebookAlbums(userID, acessToken)");
var dFacebookAlbums = {}; // dictionary
var uri = "/" + userID + "/albums?access_token=" + accessToken;
//var uri = "/me/albums";
alert("get albums uri: " + uri);
FB.api(uri, function(response)
{
alert("response: " + response);
// check for a valid response
if (response == "undefined" || response == null || !response || response.error)
{
alert("error occured");
return;
}
alert("response length: " + response.data.length);
for (var i=0, l=response.data.length; i<l; i++)
{
alert("response[key]: " + response.data[i].Name);
}
// parse JSON from response
var dJSONObjects = jQuery.parseJSON(response.data);
alert("dJSONObjects: " + dJSONObjects);
if (dJSONObjects.length == 0)
return;
// iterate through the dictionary of returned JSON objects
// and transform each to a custom facebookAlbum object
// then add each new FacebookAlbum to the final dictionary
// that will return a set of facebookAlbums
$.each(json.attributes, function () {
// add a new album to the dictionary
aFacebookAlbums[i] = FacebookAlbum(
jsonObject["id"],
jsonObject["name"],
jsonObject["location"],
jsonObject["count"],
jsonObject["link"]
);
});
});
return dFacebookAlbums;
}
It depends on the API being used. For the new Graph API single objects come back as top level object: http://graph.facebook.com/naitik -- where as collections come back with a top level data property which is an Array: http://graph.facebook.com/zuck/feed. There's also introspection to make things somewhat easier: http://developers.facebook.com/docs/api#introspection. FQL is the other popular API call, and this is where the top level response is array (think rows in SQL) which is why some examples use response[0]. Easiest thing is to just look at the response in your browser or via curl and see what it looks like.
just to clarify for all you folks who are new to FB.api (as I am) graph queries return different shaped data ... here are two examples:
FB.api('me/' function(returnData) { } ) would put the following data into returnData
{
"id": "592529630",
"name": "Hugh Abbott",
"first_name": "Hugh",
"last_name": "Abbott",
}
then if I said returnData.first_name I would get "Hugh"
If however my query was about my friends, I might run the following query
FB.api('me/friends/' function(returnData) { } )
And the shape of my data is now different:
"data": [
{
"name": "Tom Bell",
"id": "36801805"
},
{
"name": "Michael Royce",
"id": "199712888"
},
]
... so returnData is now a array ... in order to retrieve values, I would do something like the following.
returnData.data[0].name this would return "Tom Bell"
I hope this helps, as I spent a few hours wondering where I had gone wrong ... it turns out, it is all in the shape of the data !!!! good luck my friends.
Hugh
In general, the JS SDK doesn't return JSON object but it returns an object which is structured similar to the JSON Object.
Say for example : One is polling for user events data and according to the GRAPH API reference (http://developers.facebook.com/docs/reference/api/event), the returned data will have attributes as given http://developers.facebook.com/docs/reference/api/event.
The JSON object for the events data would be like this if you are using PHP SDK
Array ( [data] => Array ( [0] => Array ( [name] => sample event [start_time] => 2010-08-09T22:00:00+0000 [end_time] => 2010-08-10T01:00:00+0000 [location] => at office\ [id] => xxxxxxxx [rsvp_status] => attending )) [paging] => Array ( [previous] => hyperlink [next] => hyperlink ) )
But if you are using JS SDK, then the returned response will be like this
response.data[0...n].attributes of the particular table which you are accessing.
So, in the case of event table it will be like this :
response.data[0...n].name or response.data[0...n].id, response.data[0...n].end_time, etc
Did this ever get figured out. No one accepted anything.
alert("response[key]: " + response.data[i].Name);
The above code has Name and not name. Also, as Matti pointed out above, this works:
response.data[0].name
Just my two cents. #CoffeeAddict, accept answers to show some appreciation... Seems like someone with you rep would appreciate that. :o)
I haven't looked at the API, but I doubt FB would give you JSON encoded strings in an array. Have you tried just accessing response.data[0].someproperty?
If there is no error, then response.data should be the stuff you want (this will be an array in most cases) if you are using the new graph api. You could always just alert the JSON string if you are unsure what you are getting back.
I'm sure this must not be an issue anymore considering the Graph API explorer clearly displays the data in the form that it is returned. You are right about the difference in structure of the responses, but personally it has been useful to see what data is returned using the explorer and use the syntax accordingly.