Correct REST URI Syntax - rest

I've seen some people say that this is the only way to do REST:
/car
Displays all cars
/car/123
Displays information about the car with ID of 123
I have also seen others that prefer to do this with REST:
/car
Displays all cars
/car?id=123
Displays information about the car with ID of 123
Which is correct for REST?
Please note that I am only posting this question to get a real answer, I am not trolling. If REST is not defined enough for a definitive answer, or it is not clear which option above is "correct" for REST, then that would be a fine answer for me. I am simply trying to understand REST.
Thank you.

REST was originally designed based on a purely path-driven architecture, although different implementations of REST APIs in software like Flickr and JIRA have clouded this a bit. In the end what is most important is that the standards used within the entirety of your own API are consistent (i.e. don't use /api/user/21 for getting a user and then /api/group?id=3 for another). Ideally, use paths to locate a resource and then use different HTTP verbs to determine what you're doing with that resource (GETing it, POSTing a new one, PUTting an update, etc).
Wikipedia has a very informative article on it.. http://en.wikipedia.org/wiki/Representational_state_transfer

Related

REST API versioning - popular API's

I am trying to gather information about REST versioning. When I check forums the most preferred one seems to be to use Accept headers.
However if I check APIs of StackExchange, Google, Twitter, Yahoo, Instagram and eBay they all use versioning through URI.
I can't find why they prefer this way over HTTP headers. I would like to know the facts, not opinions. Can anyone help with this?
There really is no 'right' way to do api versioning in REST. The best article I've read explaining the different 'wrong' ways to do it is this one by Troy Hunt: Your API versioning is wrong, which is why I decided to do it 3 different wrong ways
To quote the article, he writes about three options:
URL: You simply whack the API version into the URL, for example: https://haveibeenpwned.com/api/v2/breachedaccount/foo
Custom request header: You use the same URL as before but add a header such as api-version: 2
Accept header: You modify the accept header to specify the version, for example Accept: application/vnd.haveibeenpwned.v2+json
In the comments and discussion, a few more techniques are identified:
hostname: e.g. https://v2.api.hostname.com/resource
Query String: e.g. https://api.hostname.com/resource?api-version=2.0
A variant of the accept header: application/vnd.haveibeenpwned+json; version=2.0
You wrote:
I would like to know the facts, not opinions.
Unfortunately there is no such thing as facts here - for all the reasons above, any decision is based on the opinion of the person responsible.
So, while there is a lot of argument one way or the other (see also this Best practices for API versioning? and other references Troy links to) I believe many of the 'big' services converge on the URI approach for one simple pragmatic reason:
It is the simplest to understand and implement for a novice client developer.
These services want to make it as easy as possible for the most number of client developers to interact with their api, with as little support required as possible - many of whom will have only been inspired to code at all by the desire to interact with this services' api.
Manipulating a string to construct the uri is a fairly trivial task in most client languages, and many novice developers will possibly have never heard of an accept header. So, you could consider it designed to suit the lowest common denominator of developer.

REST HATEOAS - How does the client know link semantics?

Imagine I have a fully implemented REST API that offers HATEOAS as well.
Let's assume I browse the root and besides the self link two other links (e.g. one for /users and one for /orders) are returned. As far as I have heard, HATEOAS eliminates the need for out-of-band information. How should a client know what users means? Where are the semantics stored?
I know that is kind of a stupid question, but I really would like to know that.
Suppose you've just discovered Twitter and are using it for the very first time. In your Web browser you see a column of paragraphs with a bunch of links spread around the page. You know there's a way to do something with this, but you don't know specifically what actions are available. How do you figure out what they are?
Well, you look at the links and consider what their names mean. Some you recognize right away based on convention: As an experienced Web user, you have a pretty good idea what clicking on the "home", "search" and "sign out" links is meant to accomplish.
But other links have names you don't recognize. What does "retweet" do? What does that little star icon do?
There are basically two ways you, or anyone, will figure this out:
Through experimentation, which is to say, clicking on the links and seeing what happens, then deriving a meaning for each link from the results.
Through some source of out-of-band information, such as the online help, a tutorial found through a Google search or a friend sitting next to you explaining how the site works.
It's the same with REST APIs. (Recall that REST is intended to model the way the Web enables interaction with humans.)
Although in principle computers (or API-client developers) could deduce the semantics of link relations through experimentation, obviously this isn't practical. That leaves
Convention, based on for instance the IANA 's list of standardized link relations and their meanings.
Out-of-band information, such as API documentation.
There is nothing inconsistent in the notion of REST requiring client developers to rely on something beyond the API itself to understand the meaning of link relations. This is standard practice for humans using websites, and humans using websites is what REST models.
What REST accomplishes is removing the need for out-of-band information regarding the mechanics of interacting with the API. Going back to the Twitter example, you probably had to have somebody explain to you at some point what, exactly, the "retweet" link does. But you didn't have to know the specific URL to type in to make the retweet happen, or the ID number of the tweet you wanted to act on, or even the fact that tweets have unique IDs. The Web's design meant all this complexity was taken care of for you once you figured out which link you wanted to click.
And so it is with REST APIs. It's true that in most cases, the computer or programmer will just need to be told what each link relation means. But once they have that information, they can navigate through the entire API without needing to know anything else about the details of how it's all put together.
REST doesn't eliminate the need for out-of-band information. You still have to document your media-types. REST eliminates the need for out-of-band information in the client interaction with the API underlying protocol.
The semantics are documented by the media-type. Your API root is a resource of a media-type, let's say something like application/vnd.mycompany.dashboard.v1+json, and the documentation for that media type would explain that the link relation users leads to a collection of application/vnd.mycompany.user.v1+json related to the currently authenticated user, and orders leads to a collection of application/vnd.mycompany.order.v1+json.
The library analogy works here. When you enter a library after a book, you know how to read a book, you know how to walk to a bookshelf and pick up the book, and you know how to ask the librarian for directions. Each library may have a different layout and bookshelves may be organized differently, but as long as you know what you're looking for and you and the librarian speak the same language, you can find it. However, it's too much to expect the librarian to teach you what a book is.

How to document an API and still respect HATEOAS? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm designing a REST-like API over Http.
I need the API Clients (apps, not browsers) to follow the links (HATEOAS), not to build them.
Also, I'll still use readable URLs for some reasons that can be disagreed.
However, if pretty ways to document url templates exist (like these ones), I don't think it is the right way as it could clearly tempt and legitimate developers to build urls themselves.
So, How to document an API in a way that respects HATEOAS ?
We often find Discoverability associated to HATEOAS.. To be honest, I don't think this is enough in real life : where business concepts are multiple, subtle to understand and client developers are not your teammates..
Meaningful names are clearly not enough.
Developers need to make their Client apps ..
Navigate into the API from the entry url to the relevant documents
Build valid requests (parameters and bodies) and interpret responses with no ambiguity on the semantics.
So, How to document this ?
Are there existing tools that generate documentation this way ?
Would a "Glossary" be enough to fill-in the gap between discoverability and unambiguous interpretation ?
Maybe the html representation of the API (Accept:text/html) could return human readable documentation...
.. any other idea or experience on this ?
Related concepts :
Design with Intent, Versioning, Level 3 API
First of all, there's nothing wrong with readable URIs and with users being able to easily explore your API by building URIs by hand. As long as they are not using that to drive the actual API usage, that's not a problem at all, and even encouraged by Roy Fielding himself. Disagreement on that on the basis that URIs must be opaque is a myth. Quoting Fielding himself on that matter:
Maybe I am missing something, but since several people have said that REST implies opaqueness in the URI, my guess is that a legend has somehow begun and I need to put it to rest (no pun intended).
REST does not require that a URI be opaque. The only place where the word opaque occurs in my dissertation is where I complain about the opaqueness of cookies. In fact, RESTful applications are, at all times,
encouraged to use human-meaningful, hierarchical identifiers in order to maximize the serendipitous use of the information beyond what is anticipated by the original application.
It is still necessary for the server to construct the URIs and for the client to initially discover those URIs via hypertext responses, either in the normal course of creating the resource or by some form of query
that results in a hypertext list. However, once that list is provided, people can and do anticipate the names of other/future resources in that name space, just as I would often directly type URIs into the
location bar rather than go through some poorly designed interactive multi-page interface for stock charts.
http://osdir.com/ml/web.services.rest/2003-01/msg00074.html
If you need your client developers to follow the hyperlinks and not build URIs by hand, from my experience I think the best way to do that is to promote it as a cultural change in your work environment. In my case I had a supportive manager, so it was much easier. You should warn them that the URI namespace is under control of the server and the URIs may change anytime. If their clients break because they failed to comply, it's not your responsibility. It also helps a lot to have some sort of workshop or presentation to explain how HATEOAS works and the benefits for everyone. I noticed how a lot of street-REST developers think it's superfluous, until they actually get it.
Now, to address your main question, you shouldn't document the API, you should focus your documentation efforts on your media-type. Quoting Fielding again:
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
That means, you should have custom media-types for your representations, and instead of documenting API endpoints or URIs, you should document those media-types and the operations for the links available in them. For instance, let's say you have an API for a Q&A site like StackOverflow. Instead of having an API documentation telling them that they should POST to the rel:answers link in the representation of a question in order to answer it with their current user, your questions should have a media-type of application/vnd.yourcompany.question+xml and on the documentation for that media-type you say that a POST to a rel:answers http link will answer the question.
I don't know of any existing tools for this, but from my experience, any tool that can be used to generate documentation from abstract models can be used for this.
I don't know how your ecosystem of APIs is, but what works for me is to have a generic documentation with a gentle introduction to REST, addressing some of the misconceptions, and detailed general usage to your patterns, that should apply to any API. After that, each individual server should have its own documentation, focused on the media-type.
I don't like the idea of returning documentation in the text/html representation, because that's supposed to represent the resource itself, but I love the idea of having a rel:doc link pointing to your HTML documentation for that media-type.

IM (Instant Message) Address Standard

Dear stack overflowers,
I am not sure if this is the best place for this question, but I figured I'd give it a shot.
I am currently working on an API that will allow consumers to read/write data about users. i.e. name, emails, phoneNumbers, etc. And, as you could guess by the title, I am also storing ims.
Since users may contain multiple im addresses that belong to different services (e.g. skype, google talk, AIM, etc.), there is a type attribute associated with each im address.
I am at the point where I am attempting to validate the user attributes, and when I arrived to ims I was unable to find a formal specification, or normative document that dictates how these should be formatted/validated.
My question is the following:
Is there a general format that im URI's follow?
*note:*I have stumbled upon RFC 3861 that touches on im addresses. But it seems like this isn't a standard. Additionally, there is only one example here that has the following format:
im:fred#example.com
Since emails are effectively unique identifiers, it seems reasonable that they could be represented in this way.
Could anyone shed light on this?
After looking in several sites, I was unable to find a standard that applies to all IM providers. I even looked in some API documentation (Yahoo and Jabber) without any luck. If anyone else finds anything that leads them to think any different, please share the knowledge. But as for right now, it appears I am out of luck...

HATEOAS Client Design

I have read a lot of discussions here on SO, watched Jon Moore's presentation (which explained a lot, btw) and read over Roy Fielding's blog post on HATEOAS but I still feel a little in the dark when it comes to client design.
API Question
For now, I'm simply returning xhtml with forms/anchors and definition lists to represent the resources. The following snippet details how I lay out forms/anchors/lists.
# anchors
<li class='docs_url/#resourcename'>
<a rel='self' href='resource location'></a>
</li>
# forms
<form action='action_url' method='whatever_method' class='???'></form>
# lists
<dl class='docs_url/#resourcename'>
<dt>property</dt>
<dd>value</dd>
</dl>
My question is mainly for forms. In Jon's talk he documents form types such as (add_location_form) etc. and the required inputs for them. I don't have a lot of resources but I was thinking of abstract form types (add , delete, update, etc) and just note in the documentation that for (add, update) that you must send a valid representation of the target resource and with delete that you must send the identifier.
Question 1: With the notion of HATEOAS, shouldn't we really just make the client "discover" the form (by classing them add,delete,update etc) and just send back all the data we gave them? My real question here (not meant to be a discussion) is does this follow good practice?
Client Question
Following HATEOAS, with our actions on resources being discover-able, how does this effect client code (consumers of the api) and their ui. It sounds great that following these principals that the UI should only display actions that are available but how is that implemented?
My current approach is parsing the response as xml and usin xpath to look for the actions which are known at the time of client development (documented form classes ie. add,delete,update) and display the ui controls if they are available.
Question 2: Am I wrong in my way of discovery? Or is this too much magic as far as the client is concerned ( knowing the form classes )? Wouldn't this assume that the client knows which actions are available for each resource ( which may be fine because it is sort of a reason for creating the client, right? ) and should the mapping of actions (form classes) to resources be documented, or just document the form classes and allow the client (and client developer) to research and discover them?
I know I'm everywhere with this, but any insight is much appreciated. I'll mark answered a response that answers any of these two questions well. Thanks!
No, you're pretty much spot on.
Browsers simply render the HTML payload and rely on the Human to actually interpret, find meaning, and potentially populate the forms appropriately.
Machine clients, so far, tend to do quite badly at the "interpret" part. So, instead developers have to make the decisions in advance and guide the machine client in excruciating detail.
Ideally, a "smart" HATEOS client would have certain facts, and be aware of context so that it could better map those facts to the requirements of the service.
Because that's what we do, right? We see a form "Oh, they want name, address, credit card number". We know not only what "name", "address", and "credit card" number mean, we also can intuit that they mean MY name, or the name of the person on the credit card, or the name of the person being shipped to.
Machines fail pretty handily at the "intuit" part as well. So as a developer, you get to code in the logic of what you think may be necessary to determine the correct facts and how they are placed.
But, back to the ideal client, it would see each form, "know" what the fields wanted, consult its internal list of "facts", and then properly populate the payload for the request and finally make the request.
You can see that a trivial, and obviously brittle, way to do that is to simply map the parameter names to the internal data. When the parameter name is "name", you may hard code that to something like: firstName + " " + lastName. Or you may consider the actual rel to "know" they're talking about shipping, and use: shipTo.firstName + " " + shipTo.lastName.
Over time, ideally you could build up a collection of mappings and such so that if suddenly a payload introduced a new field, and it happened to be a field you already know about, you could fill that in as well "automatically" without change to the client.
But the simply truth is, that while this can be done, it's pretty much not done. The semantics are usually way to vague, you'd have to code in new "intuition" each time for each new payload anyway, so you may as well code to the payload directly and be done with it.
The key thing, though, especially about HATEOS, is that you don't "force" your data on to the server. The server tells you what it wants, especially if they're giving you forms.
So the thought process is not "Oh, if I want a shipping invoice, I see that, right now, they want name, address and order number, and they want it url encoded, and they want it sent to http://example.com/shipping_invoice. so I'll just always send: name + "&" + address + "&" + orderNumber every time to http://example.com/shipping_invoice. Easy!".
Rather what you want to do is "I see they want a name, address, and order number. So what I'll do is for each request, I will read their form. I will check what fields they want each time. If they want name, I will give them name. If they want address, I will give them address. If they want order number, I will give them order number. And if they have any PRE-POPULATED fields (or even "hidden" fields), I will send those back too, and I will send it in the encoding they asked for, assuming I support it, to the URL I got from the action field of the FORM tag.".
You can see in the former case, you're ASSUMING that they want that payload every time. Just like if you were hard coding URLs. Whereas with the second, maybe they decided that the name and address are redundant, so they don't ask for it any more. Maybe they added some nice defaults for new functionality that you may not support yet. Maybe they changed the encoding to multi-part? Or changed the endpoint URL. Who knows.
You can only send what you know when you code the client, right? If they change things, then you can only do what you can do. If they add fields, hopefully they add fields that are not required. But if they break the interface, hey, they break the interface and you get to log an error. Not much you can do there.
But the more that you leverage HATEOS part, the more of it they make available to you so you can be more flexible: forms to fill out, following redirects properly, paying attention to encoding and media types, the more flexible your client becomes.
In the end, most folks simply don't do it in their clients. They hard code the heck out of them because it's simple, and they assume that the back end is not changing rapidly enough to matter, or that any downtime if such change does happen is acceptable until they correct the client. More typically, especially with internal systems, you'll simply get an email from the developers "hey were changing XYZ API, and it's going live on March 1st. Please update your clients and coordinate with the release team during integration testing. kthx".
That's just the reality. That doesn't mean you shouldn't do it, or that you shouldn't make your servers more friendly to smarter clients. Remember a bad client that assumes everything does not invalidate a good REST based system. These systems work just fine with awful clients. wget ftw, eh?