RESTful web service - HATEOAS - rest

I have created a quite simple RESTful web service. It only supports the GET (=read) method, e.g.:
http://localhost/application/id/xyz
The corresponding information for this ID is queried from a data source and returned as JSON.
Now my question: (How) should I implement HATEOAS in this case? Does it even make sense? I understand that HATEOAS is reasonable when having a more complex structure. But in this case, there are no other resources I could link to. The client calls the web service with a certain ID and the server returns information.
Thank you!

As you've said "The client calls the web service with a certain ID" it sounds like you've written your client to visit a specific URL in your service which has the URL to visit generated by the client, i.e. your client application already knows it can visit http://localhost/application/id/xyz for the xyz ID.
If you'd like to leverage some of the power of HATEOAS and decouple yourself from this (slight) dependency, you could instead be querying http://localhost/application/id?query=xyz which could return a list of valid links (if any exist). That way you could change the format or structure of the linked URL without issues for your client (of course, you'd still be dependent on the query URL in some way).
However, as your usage is so simple, this sounds like overkill and unnecessary work so I'd suggest you don't need to worry about HATEOAS until you have a more complex system or clients :)

In HATEOS your return value is not an ID but a URL. Invoking that URL links you to the next resource in the web. Just like a web page containing links to other web pages.

Related

REST API design for resource modification: catch all POST vs multiple endpoints

I'm trying to figure out best or common practices for API design.
My concern is basically this:
PUT /users/:id
In my view this endpoint could by used for a wide array of functions.
I would use it to change the user name or profile, but what about ex, resetting a password?
From a "model" point of view, that could be flag, a property of the user, so it would "work" to send a modification.
But I would expect more something like
POST /users/:id/reset_password
But that means that almost for each modification I could create a different endpoint according to the meaning of the modification, i.e
POST /users/:id/enable
POST /users/:id/birthday
...
or even
GET /user/:id/birthday
compared to simply
GET /users/:id
So basically I don't understand when to stop using a single POST/GET and creating instead different endpoints.
It looks to me as a simple matter of choice, I just want to know if there is some standard way of doing this or some guideline. After reading and looking at example I'm still not really sure.
Disclaimer: In a lot of cases, people ask about REST when what they really want is an HTTP compliant RPC design with pretty URLs. In what follows, I'm answering about REST.
In my view this endpoint could by used for a wide array of functions. I would use it to change the user name or profile, but what about ex, resetting a password?
Sure, why not?
I don't understand when to stop using a single POST/GET and creating instead different endpoints.
A really good starting point is Jim Webber's talk Domain Driven Design for RESTful systems.
First key idea - your resources are not your domain model entities. Your REST API is really a facade in front of your domain model, which supports the illusion that you are just a website.
So your resources are analogous to documents that represent information. The URI identifies the document.
Second key idea - that URI is used by clients to cache representations of the resource, so that we don't need to send requests back to the server all the time. Instead, we have built into HTTP a bunch of standard ways for communicating caching meta data from the server to the client.
Critical to that is the rule for cache invalidation: a successful unsafe request invalidates previously cached representations of the same resource (ie, the same URI).
So the general rule is, if the client is going to do something that will modify a resource they have already cached, then we want the modification request to go to that same URI.
Your REST API is a facade to make your domain model look like a web site. So if we think about how we might build a web site to do the same thing, it can give us insights to how we arrange our resources.
So to borrow your example, we might have a web page representation of the user. If we were going to allow the client to modify that page, then we might think through a bunch of use cases (enable, change birthday, change name, reset password). For each of these supported cases, we would have a link to a task-specific form. Each of those forms would have fields allowing the client to describe the change, and a url in the form action to decide where the form gets submitted.
Since what the client is trying to achieve is to modify the profile page itself, we would have each of those forms submit back to the profile page URI, so that the client would know to invalidate the previously cached representations if the request were successful.
So your resource identifiers might look like:
/users/:id
/users/:id/forms/enable
/users/:id/forms/changeName
/users/:id/forms/changeBirthday
/users/:id/forms/resetPassword
Where each of the forms submits its information to /users/:id.
That does mean, in your implementation, you are probably going to end up with a lot of different requests routed to the same handler, and so you may need to disambiguate them there.

RESTful vs. SEO Urls

So I have a dilema here. Trying to build out a RESTful API. Which means I'd like to have resources defined and also require that consumers reference those resources by id.
For example, the typical {resourceName}/{id}?{querystring}
But the way of course a web UI works, for a ecommerce site is that naturally you have SEO-friendly urls.
So there is a mismatch in terms of application specific URLs where we have application context based urls, context here being an ecommerce site using SEO-friendly URLs. They wouldn't have stuff like /id in it 100% of the time. And actually our site doesn't have any ids whatsoever in the web UI's urls.
So when users go from page to page, we might have urls like www.ourdomain.com/cars/local/usa/ca/sunnyvale-cars. And sometimes we're talking about stripping the '-' or other characters out of the more seo friendly urls, after the UI devs send a request to lets say like above a state resource. I'd strip the city name out of 'sunnyvale-cars' if lets say I wanted info on that city so the UI team might send me '/cities?name=sunnyvale-cars' where our API would need to strip out the city name in order to do the query in the backend which to me just doesn't sound like something our API should be doing. It's also coupling our REST API to the web and web conventions...our REST API should be ignorant of any type of delivery mechanism so that our API can be reused for other apps or other APIs in our Business domain.
There might be times where the UI Engineering team, in fact a lot of times they'll only have URLs like this. There is no user action or lets say dropdown list where they can just grab an id. So they can't always request stuff for the next page by sending me a RESTful URI request every time as they may not have ids all the time. In other words, sometimes they'll have to instead request stuff like this: /states?name="ca" to get something related to that state just as a hypothetical example.
So how in the world do you even build a REST API if your UI team is telling you they won't have ids for everything?
From a REST purist's point of view no URI is inherently more RESTful than another as long as both use identify the resources. At least, I could not find anything about that in the original thesis.
However, if you find some structure fitting the purposes of your API better, you can create a second endpoint exclusively for the needs of your UI team. That endpoint would serve as a proxy and simply map the SEO-friendly structure to your API in possibly generic way.
Or, applications from the outside are just expected to do the rewriting or any app specific mapping-to-REST API "stuff" since it's really app specific in what that mapping looks like anyway, thus keeping the API ignorant of application specific details, domain logic, or even web conventions which the API should not care about or even know about.

API Endpoint Design : Technical Spec or Product

We have 2 developers who have conflicts in the way to design the RESTful API Endpoint. Basically, let say that we have Facebook product in hand, one table for the posts.
First developer give the opinions that
We should seperate Endpoint by product, not by the technical storage. To be like that, we will have endpoint for user facebook post and other facebook post.
/v1/wall/mypost
/v1/wall/other
To be like that, we be able to configure each products that may return difference results
Second developer disagree, give the opinions that
If be like that, it will make infinite endpoint. it will have /wall/someone, /wall/sometwo.
We should have single endpoint, and just let that be a part of query. ex. /wall?user=someone, /wall?user=sometwo
The endpoint should be look like technical schema, it return the same result, why it have to seperated to make it more jobs on maintenance the code.
What is the good practice to design our endpoint? Is it should be endpoint by the product? or is it should be by schema?
It should depend on what 'resource' that the service is suppose to manage from the API user perspective and not from the internal implementation.
With that, if the service is to manage say, a resource that can be identified by 'someone', 'sometwo' and, then the correct way to model it is
/wall/someone/
/wall/sometwo/
In this case, 'someone' and 'sometwo' are two different resources and you could have infinite # of them; but that has nothing to do with the internal storage or implementation.
On the backend, there should be some url pattern to extract 'someone' and 'sometwo' as resource and map them into internal implementation details.
What are these "endpoints" you speak of? That's SOAP terminology! RESTful web services are defined in terms of "resources" that are uniquely identified by URL.
A resource typically represents an entity in your domain model (e.g., a user). The ID of the entity is typically used as a path element ("path parameter" in the lingo of most REST libraries, such as JAX-RS) in the URL. Query parameters should only be used to sort/filter results on the server side.
Your first developer is closer to being correct.

RESTful API Architecture

I'm developing a project to be used by both a smartphone app and a single page app website. I'm using Backbone.js for my data binding.
I've got a bit of an architectural question: How do I make my API restful, yet enrich the data coming back in my models.
An example:
I would like to change the roles of a user in a group.
In the restful case, I'd load a collection of the roles for a particular user in the group. I'd check and uncheck the roles I'd like to apply to the user in the context of that group, then save. I'm therefore doing a GET for the array of roles and a PUT to save the altered list. The issue I am facing is that I need to enrich my model with more meta data such as the Group's name, the User's name etc so the user has some context when editing the data.
I can quite easily do this but then I'm not really restful anymore with my model.
Does anyone have any resources they can point me to that can help me to architect my solution to achieve the best of both RESTfulness and usability using Backbone.js?
Backbone model does not make your application more or less restful.
For the most part, rest is about the interactions between the HTTP client and server.
Like in REST API URI Design Approach question, mostly the focus is on the URI design.
The more practical way of thinking or applying REST as the starting point (at least it works for me) is to think in the following ways:
1) Use only HTTP ‘GET/POST/PUT/DELETE’ as the way to model your domain ‘actions’ . Just like when you dealing with database, all your actions are mapped to CURD.
2) URI/URL is to identify resources only. Should never have any ‘actions’ in your URI.
3) The data exchanged should be in the body of the HTTP messages.
Just to simplify the discussions, not getting into how to model the data itself
Two great books on rest.
REST in Practice
Restful Web Services
You can create a Restful web service which can be consumed in both smartphone app and a single page app website.
Please have a look at
http://blogs.msdn.com/b/hongyes/archive/2012/08/30/single-page-application-with-backbone-js-and-asp-net-web-api.aspx
Here they are creating SPA with backbone.js and ASP.NET Web API ( to create Restful web service).
Other great resource can be found here:
http://www.asp.net/single-page-application/overview/templates/backbonejs-template
Thanks.

RESTful HATEOAS Client Url

I'm reasonably sure I understand the server-side of HATEOAS design - returning state URL's in the response - but I'm slightly confused about how to design a client to accept these.
For instance, we access a resource at //somehost.com/resource/1 - this provides us with the resource data and links. We'll assume POST to //somehost.com/resource is returned, indicating a 'new' action. Now I understand posting some data to that url creates a new resource, and provides a response, but where does the form to post that data reside? I've seen implementations where //somehost.com/resource/1/new provides a form which POSTS to /resource, but that URL itself contains a verb, and seems to violate REST.
I think my confusion lies in that I'm implementing a RESTful API and a client to consume it, within the same application.
Is there some sort of best-practice for this sort of thing?
I've seen implementations where //somehost.com/resource/1/new provides a form which POSTS to /resource, but that URL itself contains a verb, and seems to violate REST.
This is incorrect. A URI containing a verb does not, in itself, violate any REST constraint. It is only when that URI represents an action that this becomes a violation. If you can perform a GET request on the URL and receive some meaningful resource (such as a "create new resource" form), then that is perfectly RESTful, and good practice.
My own API is exactly as you describe: /{collection}/new returns a form. /new is just shorthand for a hypothetical /new-resource-creation-form and still represents a noun, and only supports GET requests (HEAD, OPTIONS and TRACE not withstanding).
What HATEOAS prohibits is the user agent being required to know, that in order to create a new resource, it must add /new to the name of the collection.
Basically, if you implement your API as (X)HTML, and can surf it in a browser and perform all actions (AJAX may be required for non-POST form submissions until HTML and browsers catch up with HTTP), then it complies with the hypermedia constraint of REST.
EDIT promoted from comments:
As long as the response negates any need for a priori knowledge, it conforms to the hypermedia constraint. If the client claims to understand HTML, and you send back a response containing a link to an external stylesheet or javascript (no matter where that is hosted) which the client needs to be able to render the page correctly, then it is reasonable to say that the constraint is met. The client should know how to handle all media types it claims to support. A normal human web browser is the perfect example of a client with no out-of-band knowledge about any one HTTP service (web site).
Just to say it explicitly, a web site is a kind of HTTP service. Web browsers do not treat different web sites differently. In order to search for products on Amazon, you load the Amazon service endpoint at http://amazon.com/ and follow links or fill out forms provided in that response. In order to search for products on eBay, you load the eBay service endpoint at http://ebay.com/ and do the same.
Browsers don't know in advance that for searching eBay you must do this, but for searching Amazon you have to do that. Browsers are ignorant. Clients for other HTTP services should be ignorant too.
Yes, you could provide a URI that returns a form for resource creation. Conceivably the form could be used for dynamic discovery of the elements needed to construct a new resource (but you'd want to decide how practical that would really be in a machine-to-machine environment).
Unless there is a requirement that somehow the API has an exact browser-surfable equivalent, the documentation of the media type will describe what elements are needed.
Remember that documentation of media types and the allowed HTTP verbs for a resource is not contrary to RESTful principles. Look at the SunCloud API for an example.
Indeed, according to your example, POST'ing to
//somehost.com/resource
to create a new resource is more standard than first returning a form
//somehost.com/resource/1/new
and THEN POST'ing to
//somehost.com/resource
anyway.