How to customize the Restlet's error message - customization

I used Restlet framework to provide the RESTful service.
I used the ResouceException the return the HTTP ERROR CODE, like 400 Bad Request, and so on.
I "new" the ResourceException(code, name, desc, uri) with the code, name and desc. I get the following output:
Bad Request (name)
period is not a number (desc)
You can get technical details here. (uri,though I didn't provide it)
Please continue your visit at our home page. (home page, I didn't provide, too)
I think the last two sentences is no use for user to correct the "bad request.".
Can I remove them? How to do? Or If I want to output sth else, how to customize the message.
Thanks a lot.

You could replace the default StatusService with one of your own.
Extending the class and Overriding getRepresentation(Status, Request, Response) to provide the format you would like.
this can then be set in your Application using setStatusService(StatusService)
There may be a slightly more up to date way to do this as the method I am using has survived a few Restlet updates, now but it still works.
Update
as of restlet version 2.3.x
the method to override is toRepresentation(Status, Request, Response)

Related

Get page insights and post insights in the same request

Hello i am trying to get page level insights and post level insights in the same request but cant seem to get the syntax correct.
page id /published_posts?fields=permalink_url,created_time,message,shares,reactions.limit(0).summary(1),comments.limit(0).summary(1),insights.metric(post_reactions_by_type_total,post_impressions_unique,page_posts_impressions_organic)&since=yesterday
This is my request for now but i wanna add page insights like page_fans and page_fans_city.
How can i do that?
You are using the published_posts endpoint there already, you can not go back “up” to the page object from there. You need to rewrite the whole thing so that you use the page id itself as the basic endpoint, and then request everything else via the fields parameter. The trick is to get the syntax and nesting right …
/page-id?fields=insights.metric(page_fans,page_fans_city),published_posts{…}
should work, inside the {…} you then put all the original fields you requested from the published_posts endpoint before, so
/page-id?fields=insights.metric(page_fans,page_fans_city),published_posts{permalink_url,
created_time,…,insights.metric(post_reactions_by_type_total,post_impressions_unique,
page_posts_impressions_organic)}
And &since=yesterday then just goes at the end again, after all that.
To have the since limitation still apply on the post level, it apparently needs to be added on that “field” again, syntax similar to .metric():
?fields=…,published_posts.since(yesterday){…}

API RESTful Resource Naming

I always have the doubt that you can see below when i need to create theresource URLs for a REST API. I wonder if some one can help me.
Let's suppose that i have two models.
User
Post
User can submit his own posts and can comment his own and another posts.
Main resources URLs for User would be:
GET /users # Retrieve all users.
POST /users # Create a new user.
GET/DELETE/PUT /users/{user_id} # Get, remove and update an user.
Main resource URLs for Post would be:
GET /posts # Retrieve all posts.
POST /posts # Create a new post.
GET/DELETE/PUT /posts/{post_id} # Get, remove and update a post.
My problem come when for example i want:
Top 10 submitters (filter for a parameter(external link, discussion, all)). The URL should be:
GET /users/top?type=ext
GET /users/top?type=disc
GET /users/top # for all
Or maybe it should be:
GET /users?top=ext
GET /users?top=disc
GET /users?top=all
The same but with posts:
Top 10 commented post (filter for a parameter(external link, discussion, all)). The URL should be:
GET /posts/comments?type=ext
GET /posts/comments?type=disc
GET /posts/comments # for all
Or maybe it should be:
GET /posts?top=ext
GET /posts?top=disc
GET /posts?top=all
Any of above options are good for you or it should be another way?
Regards
I like to think of the REST URI as a model representation in itself.
So /users/top doesn't make a lot of sense but /posts/comments seems to be fine (as comments could also be a different model). But for your case, I recommend other set of query parameters as they're widely used for filtering & sorting requests. So in your case, I'd recommend something like:
GET /users?sort=ext&order=desc&limit=10
which would help me understand that I'm requesting 10 user resources which have been sorted for ext in the descending order. (you can even change it to type=ext if you want)
As usual; REST doesn't care what spellings you use.
One place you might look for inspiration is... stack overflow itself. Do these URI look familiar?
/questions?sort=newest
/questions?sort=featured
/questions?sort=votes
The API has pretty decent documentation, which will also offer hints at decent spellings to deal with paging and search ranges.
That said, IMDB takes a different approach - The Shawshank Redemption uses a straight forward "I am an element of a collection" spelling
http://www.imdb.com/title/tt0111161/
But the top rated titles of all time? they appear as a chart
http://www.imdb.com/chart/top
But i want to know if there is a standard according to #Hawkes answer or there is no standard at all.
No standard at all; just local spelling conventions. Which is, to some degree, part of the point of REST: the server can use whatever spellings for URI make sense, and the client just "follows its nose" based on its understanding of the processing rules for the media type and the data provided by the server.

Correct REST API URL format for related objects

I'm designing a REST API where, amongst others, there are two objects.
Journey
Report
For each Journey there are many Reports enroute, and each Report has exactly one associated Journey.
A user might create a Journey using the API as follows...
POST /journey/
Then retrieve the details...
GET /journey/1226/
The first question is, if a user wanted to post an Report to their Journey, which is the 'correct' URL structure that the API should impose? This seems intuitive to me...
POST /journey/1226/report/
...or is this the case...
POST /report/
...whereby in the latter, the Journey ID is passed in the request body somewhere?
The second question is, how might one go about implementing the first case in a tool such as the Django REST framework?
Thanks!
The URL/URI structure is almost completely irrelevant. It is nice to be able to read it, or easily change or even guess it, but that is it. There is no "requirement" official or unwritten how they should look like.
The point is however, that you supply the URIs to your clients in your responses. Each GET will get you a representation that contains links to the next "states" that your client can reach. This means the server has full control over URI structure, the client usually has to only know the "start" or "homepage" URI, and that's it.
Here is an article which discusses this question, has some good points: http://www.ben-morris.com/hackable-uris-may-look-nice-but-they-dont-have-much-to-do-with-rest-and-hateoas/
Pass for the second question :) I didn't use that particular framework.

Zero-length URL Segments

Using the latest versions of Flask and Flask-RESTful, I have some very basic routes defined as such:
def build_uri_rules(uri_map):
for cls, uri in uri_map.iteritems():
api.add_resource(cls, uri)
uris = {
SampleController: '/samples/<string:hash_or_id>',
SampleFamilyController: '/samples/<string:hash_or_id>/family',
}
build_uri_rules(uris)
This works for uris requested 'properly', but what if the /samples/ endpoint is hit without a parameter, or the sample*family endpoint is hit with an empty sample id? Currently, this results in a 404 error. This works well enough, but I believe the proper thing here would be to throw a 400 error, as they found a proper URL but their data is improperly structured. Is there a way that I can force this behavior?
As a side note:
Looking through the Werkzeug docs, I see that werkzeug.routing allows a minimum length for certain url parameters, but I also see that it's got a minimum of 1. Admittedly, I've not look for why this is the case, but would this be the right tree to bark up? or should I rather simply create a global 404 handler that checks for the length of the parameter and raise the proper error from there?
Thanks!
EDITED: For code correctness.
I would say that hitting /samples/ or /samples/family (or even /samples//family) should result in a 404 as there is nothing at that endpoint.
If, however, you want to do otherwise, the simplest way to handle it would be create a 404 handler for just /samples/ and /samples/family that returns a note with more information about what the consumers of your API are most likely doing wrong.
uris = {
Explanitory400Controller: '/samples/',
SampleController: '/samples/<string:hash_or_id>',
Explanitory400Controller: '/samples/family',
SampleFamilyController: '/samples/<string:hash_or_id>/family',
}

Read AICC Server response in cross domain implementation

I am currently trying to develop a web activity that a client would like to track via their Learning Management System. Their LMS uses the AICC standard (HACP binding), and they keep the actual learning objects on a separate content repository.
Right now I'm struggling with the types of communication between the LMS and the "course" given that they sit on two different servers. I'm able to retreive the sessionId and the aicc_url from the URL string when the course launches, and I can successfully post values to the aicc_url on the LMS.
The difficulty is that I can not read and parse the return response from the LMS (which is formatted as plain text). AICC stipulates that the course start with posting a "getParam" command to the aicc_url with the session id in order to retrieve information like completion status, bookmarking information from previous sessions, user ID information, etc, all of which I need.
I have tried three different approaches so far:
1 - I started with using jQuery (1.7) and AJAX, which is how I would typically go about a same-server implementation. This returned a "no transport" error on the XMLHttpRequest. After some forum reading, I tried making sure that the ajax call's crossdomain property was set to true, as well as a recommendation to insert $.support.cors = true above the ajax call, neither of which helped.
2 & 3 - I tried using an oldschool frameset with a form in a bottom frame which would submit and refresh with the returned text from the LMS and then reading that via javascript; and then a variation upon that using an iFrame as a target of an actual form with an onload handler to read and parse the contents. Both of these approaches worked in a same-server environment, but fail in the cross-domain environment.
I'm told that all the other courses running off the content repository bookmark as well as track completion, so obviously it is possible to read the return values from the LMS somehow; AICC is pitched frequently as working in cross-server scenarios, so I'm thinking there must be a frequently-used method to doing this in the AICC structure that I am overlooking. My forum searches so far haven't turned up anything that's gotten me much further, so if anyone has any experience in cross-domain AICC implementations I could certainly use recommendations!
The only idea I have left is to try setting up a PHP "relay" form on the same server as the course, and having the front-end page send values to that, and using the PHP to submit those to the LMS, and relay the return text from the LMS to the front-end iframe or ajax call so that it would be perceived as being within the same domain.... I'm not sure if there's a way to solve the issue without going server-side. It seems likely there must be a common solution to this within AICC.
Thanks in advance!
Edits and updates:
For anyone encountering similar problems, I found a few resources that may help explain the problem as well as some alternate solutions.
The first is specific to Plateau, a big player in the LMS industry that was acquired by Successfactors. It's some documentation that provide on setting up a proxy to handle cross-domain content:
http://content.plateausystems.com/ContentIntegration/content/support_files/Cross-domain_Proxlet_Installation.pdf
The second I found was a slide presentation from Successfactors that highlights the challenge of cross-domain content, and illustrates so back-end ideas for resolving it; including the use of reverse proxies. The relevant parts start around slide 21-22 (page 11 in the PDF).
http://www.successfactors.com/static/docs/successconnect/sf/successfactors-content-integration-turley.pdf
Hope that helps anyone else out there trying to resolve the same issues!
The answer in this post may lead you in the right direction:
Best Practice: Legitimate Cross-Site Scripting
I think you are on the right track with setting up a PHP "relay." I think this is similar to choice #1 in the answer from the other post and seems to make most sense with what you described in your question.