What is the advantage of using REST instead of non-REST HTTP?
Asked Answered
S

14

176

Apparently, REST is just a set of conventions about how to use HTTP. I wonder which advantage these conventions provide. Does anyone know?

Slemmer answered 3/2, 2010 at 9:55 Comment(1)
see also Why we should use rest?Pierette
W
178

I don't think you will get a good answer to this, partly because nobody really agrees on what REST is. The wikipedia page is heavy on buzzwords and light on explanation. The discussion page is worth a skim just to see how much people disagree on this. As far as I can tell however, REST means this:

Instead of having randomly named setter and getter URLs and using GET for all the getters and POST for all the setters, we try to have the URLs identify resources, and then use the HTTP actions GET, POST, PUT and DELETE to do stuff to them. So instead of

GET /get_article?id=1
POST /delete_article   id=1

You would do

GET /articles/1/
DELETE /articles/1/

And then POST and PUT correspond to "create" and "update" operations (but nobody agrees which way round).

I think the caching arguments are wrong, because query strings are generally cached, and besides you don't really need to use them. For example django makes something like this very easy, and I wouldn't say it was REST:

GET /get_article/1/
POST /delete_article/     id=1

Or even just include the verb in the URL:

GET /read/article/1/
POST /delete/article/1/
POST /update/article/1/
POST /create/article/

In that case GET means something without side-effects, and POST means something that changes data on the server. I think this is perhaps a bit clearer and easier, especially as you can avoid the whole PUT-vs-POST thing. Plus you can add more verbs if you want to, so you aren't artificially bound to what HTTP offers. For example:

POST /hide/article/1/
POST /show/article/1/

(Or whatever, it's hard to think of examples until they happen!)

So in conclusion, there are only two advantages I can see:

  1. Your web API may be cleaner and easier to understand / discover.
  2. When synchronising data with a website, it is probably easier to use REST because you can just say synchronize("/articles/1/") or whatever. This depends heavily on your code.

However I think there are some pretty big disadvantages:

  1. Not all actions easily map to CRUD (create, read/retrieve, update, delete). You may not even be dealing with object type resources.
  2. It's extra effort for dubious benefits.
  3. Confusion as to which way round PUT and POST are. In English they mean similar things ("I'm going to put/post a notice on the wall.").

So in conclusion I would say: unless you really want to go to the extra effort, or if your service maps really well to CRUD operations, save REST for the second version of your API.


I just came across another problem with REST: It's not easy to do more than one thing in one request or specify which parts of a compound object you want to get. This is especially important on mobile where round-trip-time can be significant and connections are unreliable. For example, suppose you are getting posts on a facebook timeline. The "pure" REST way would be something like

GET /timeline_posts     // Returns a list of post IDs.
GET /timeline_posts/1/  // Returns a list of message IDs in the post.
GET /timeline_posts/2/
GET /timeline_posts/3/
GET /message/10/
GET /message/11/
....

Which is kind of ridiculous. Facebook's API is pretty great IMO, so let's see what they do:

By default, most object properties are returned when you make a query. You can choose the fields (or connections) you want returned with the "fields" query parameter. For example, this URL will only return the id, name, and picture of Ben: https://graph.facebook.com/bgolub?fields=id,name,picture

I have no idea how you'd do something like that with REST, and if you did whether it would still count as REST. I would certainly ignore anyone who tries to tell you that you shouldn't do that though (especially if the reason is "because it isn't REST")!

Whoosh answered 23/10, 2012 at 15:41 Comment(17)
POST and PUT are meant to be used per the HTTP RFC. In this case, PUT means to create/update something at a specific location - which occurs depends on whether something's already there at the URI (and it's also idempotent) while POST means you ask the web service to determine where to put what you're sending it - and then it returns you the URI (so it's create only). Can't really complain about english, not when it's completely off to use DELETE when referring to anything off the computer. I am wondering about what to do with regards to the issue brought up in your edit, though :PElin
The Facebook API example looks like REST to me (actually far more so that your examples using verbs in the URLs). There is no reason why query parameters cannot be RESTful, it is just good practice to use paths where data can be arranged in hierarchy.Bolshevik
Query strings are perfectly RESTful so long as you're not making references to resources in them. I tend to think of them more like filters that can tweak the behavior of the endpoint.Olfactory
This is by far the most enlightening explanation I've seen. One question: can you give an example of a web app whose actions are not easily mapped to CRUD?Antipyrine
The best thing I can think of on the spot is something like triggering a doorbell. It's a transient action that doesn't really affect state. Ok yes technically you could do something like PUT /doorbell/is_ringing true (which immediately becomes false), but it seems less hacky do POST /ring/doorbell to me.Whoosh
-1, REST is something very specific - as described by Roy Fielding when he invented it. See this answer. particularly: "The client needs only know the initial URI, and subsequently chooses from server-supplied choices to navigate or perform actions.". Basically, if any part of an API documents endpoints, e.g. says "given a user id, you can get user info at /user/{id}, then it's not restful. Consider: does your browser have to come preprogrammed knowing how to get the HTML for a stackoverflow question page?Rhu
(continued...) That other people misuse the term doesn't change what it is. Disclaimer, though: I am still just learning what REST is and this is what clicked for me recently.Rhu
@Rhu Isn't your example a bit extreme? Writing an endpoint into the documentation does not make it non-REST as long as users are properly advised not to rely on it if they'd like to build a proper and durable client. In the end we can't deny that docs have a merit and one of the reasons REST-like techs have came up so long is they can be understood and used easily.Diet
@infiniteRefactor: No, it's just what the author of REST defined REST to mean. This is what allows you to be able to use Google and Stackoverflow and Wikipedia without having to memorize their internal URLs. It's pretty great. Also I see the vast majority of services not needing to be REST in the true sense of the word (as the author intended). That being said, REST has come to have a different meaning nowadays and given the momentum it'll probably stick for goodRhu
So you mean to say we cannot do GET /products/1 without using REST? I don't know whether we can do that without RESTful or notHabitable
I still don't understand why GET /person/1 is fundamentally so much better than ?action=person.get&id=1. In fact it seems worse, because the name of the field referenced by id=1 is implicit in the REST-style URL, so it needs to be agreed upon in advance by both the server and the client. I also don't see how REST better decouples the URL from the server implementation; in either case a front controller has to route the request to some handler, either by parsing path segments and HTTP verbs, or by parsing URL variables. What's the big difference? Why are so many APIs today REST?Creamy
@Whoosh As you said Instead of having randomly named setter and getter URLs and using GET for all the getters and POST for all the setters, we try to have the URLs identify resources, and then use the HTTP actions GET, POST, PUT and DELETE to do stuff to them , Probably this was correct 5 years back(in plain servlet ) but now a day every MVC framework (spring/struts) identify the resources with URLs where url are mapped on top of method names in MVC controller. Is n't it ? So now a days I do not see any difference b/w Rest and non Rest HTTP approach ?Barrada
Your answer got me on the start: "nobody really agrees on what REST is"Supermundane
@Rhu i don't understand what you mean. I type google.com, and Google gives me a frontend of their own design. It's Google communicating with Google. They could be communicating in whatever way they want, they don't need to comply with REST.Posthaste
@JuanPerez they need to comply with REST -- which they do by serving it using HTML -- so that any browser can display it correctly without the browsers having to know any specifics of google.com's webpage. how google internally handles its internal URLs isn't what REST in the proper use of the term is referring toRhu
@Rhu that's amazing, i didn't know that. You're saying there's no "google frontend", and instead the backend delivers both the data and the actual page where it is displayed!Posthaste
@JuanPerez ya exactly, this is how HTML works :) it is indeed an ingenious inventionRhu
P
53

Simply put, REST means using HTTP the way it's meant to be.

Have a look at Roy Fielding's dissertation about REST. I think that every person that is doing web development should read it.

As a note, Roy Fielding is one of the key drivers behind the HTTP protocol, as well.

To name some of the advandages:

  • Simple.
  • You can make good use of HTTP cache and proxy server to help you handle high load.
  • It helps you organize even a very complex application into simple resources.
  • It makes it easy for new clients to use your application, even if you haven't designed it specifically for them (probably, because they weren't around when you created your app).
Pail answered 3/2, 2010 at 9:57 Comment(10)
"Simple": Why is REST simpler than HTTP?Slemmer
"helps you organize": So this organization is more difficult when merely using GET and POST?Slemmer
"It makes it easy for new clients to use your application": this is about REST vs. plain HTTP, right?Slemmer
Conforming to REST constraints is definitely not simple. Squeezing complex business operations into four standard verbs is actually really hard sometimes. However, when done well, the end result can be simple to comprehend, but getting there is anything but.Reportorial
@Dimitri: "Simple" because it gives you a simple framework to work with. REST is HTTP! It's way more simple than SOAP (which even has simple in its name). "helps you organize" - the concept is not very hard to comprehend and, once implemented correctly - it makes things very well. REST can be though as a way of designing the app, rather then an implementation detail. As Darrel points out implementing it might not be easy, but the result is rewarding. "It makes it easy for new clients to use your application" - Again: REST is HTTP.Pail
Weren't PUT and DELETE meant for file/disc operations?Clipper
@DarrelMiller I thought it was just me that thought that. I have an API that sometimes needs several variables and it is hard to cram everything into the REST format to somehow make it "simpler."Outoftheway
this answer is not comparing rest and html as op asked, its comparing rest with other alternatives.Sarrusophone
-1 for do not know how to choose a http method for user login/forgot password api? GET?POST?PUT? Try to match http method to business logic is useless. So just use POST and json.Tallyho
@AndreiV PUT and DELETE are file operations if GET returns file contents, if the resource is not a disk file they are not file operations.Shluh
C
33

Simply put: NONE.

Feel free to downvote, but I still think there are no real benefits over non-REST HTTP. All current answers are invalid. Arguments from the currently most voted answer:

  • Simple.
  • You can make good use of HTTP cache and proxy server to help you handle high load.
  • It helps you organize even a very complex application into simple resources.
  • It makes it easy for new clients to use your application, even if you haven't designed it specifically for them (probably, because they weren't around when you created your app).

1. Simple

With REST you need additional communication layer for your server-side and client-side scripts => it's actually more complicated than use of non-REST HTTP.

2. Caching

Caching can be controlled by HTTP headers sent by server. REST does not add any features missing in non-REST.

3. Organization

REST does not help you organize things. It forces you to use API supported by server-side library you are using. You can organize your application the same way (or better) when you are using non-REST approach. E.g. see Model-View-Controller or MVC routing.

4. Easy to use/implement

Not true at all. It all depends on how well you organize and document your application. REST will not magically make your application better.

Companionate answered 10/12, 2012 at 8:35 Comment(11)
typically rest apis are easier to cache because you separate out data into resources that have the same lifecycle (are created and updated at the same time) so that you can reliably cache and cache bust - while non -rest-apis often return data that has been heavily post processed or is a conglomeration of multiple entities making it harder to cacheVogel
@ScottSchulthess I don't think REST and non-REST API's differ in this. You can still have poorly organized REST API and well organized non-REST API.Companionate
correct it's not mutually exclusive (you can have a non-rest api that is cacheable) but taking a rest approach to api design encourages and in practice it's definitely relevant as it encourages various best practices (discoverability, generic interfaces, cachability, intelligent resource modelling)Vogel
"REST does not help you organize things. It forces you to use API supported by server-side library you are using." I'm not sure what you mean by this. It's perfectly possible (and not anymore difficult than constructing a non-REST API) to create a RESTful API without using an extra server-side framework.Childbirth
"With REST you need additional communication layer" - humbug, you can use your existing HTTP library just fine.Scorecard
@SørenBoisen This answer is bit old. I should probably update it to reflect more the current state of things.Companionate
Fair enough, there was a time when many HTTP client libs only offered GET and POST, which was a real bother :)Scorecard
I am sad so many people upvoted this. What you are suggesting is HTTP has caching headers... well HTTP is using REST principles. That's why REST is great. REST is not something that extends HTTP.. REST is just series of requirements for networking protocols, which HTTP complies.. and which our APIs should comply, because HTTP is great why reinvent the wheel and not make our APIs utilize HTTP functions and stay RESTful.. duhhh..... I can't stop putting more dots....Tailwind
@Tailwind Yes, I have to update the answer when I get a bit of free time. This was written long time ago when using REST was hard both on front end and back end because of lack of libraries or browser support.Companionate
@Tailwind That said I'd still say that using REST is not critical in app design and if you'd need to overcome some serious drawbacks it's probably not worth it (there might be none nowadays) Standardising stuff is always good though.Companionate
No worries. Nobody on this page understands what REST is.Abjuration
R
27

IMHO the biggest advantage that REST enables is that of reducing client/server coupling. It is much easier to evolve a REST interface over time without breaking existing clients.

Reportorial answered 3/2, 2010 at 12:31 Comment(7)
Could you give an example? Thanks!Jordans
Wouldn't that depend on how abastracted your non-REST API was?Outoftheway
@Outoftheway It is possible, but unlikely. The constraints of REST were chosen to explicitly enable independent evolution of components. If you have found a way to do this better without applying the same constraints, then I'm sure lots of people would like to hear about it.Reportorial
@DarrelMiller Can you please elaborate How REST reduces the client/server coupling better than Non REST http approach ? I believe you are pointing towards the point Timmmm said in his/her answer. Please see mine latest comment under Timmmm answerBarrada
@Barrada REST systems don't rely on out of band information to be able to process the response. There are no assumptions that need to be made about what might come back from a particular request. The response tells you everything you need to know. This allows a server to change its behavior and the client can be aware of those changes.Reportorial
@DarrelMiller But that is true for http also. Can you give any example that it is true for Rest only but not for http ?Barrada
@Barrada Yes, the REST constraints tell you how to use a protocol like HTTP to achieve evolvable systems, but that doesn't mean people don't use HTTP in ways that don't follow these guidelines. Almost every API that returns Content-Type: application/json has clients that rely on out of band knowledge to get semantic information from that payload. That violates REST's constraints but not the HTTP spec.Reportorial
D
17

Discoverability

Each resource has references to other resources, either in hierarchy or links, so it's easy to browse around. This is an advantage to the human developing the client, saving he/she from constantly consulting the docs, and offering suggestions. It also means the server can change resource names unilaterally (as long as the client software doesn't hardcode the URLs).

Compatibility with other tools

You can CURL your way into any part of the API or use the web browser to navigate resources. Makes debugging and testing integration much easier.

Standardized Verb Names

Allows you to specify actions without having to hunt the correct wording. Imagine if OOP getters and setters weren't standardized, and some people used retrieve and define instead. You would have to memorize the correct verb for each individual access point. Knowing there's only a handful of verbs available counters that problem.

Standardized Status

If you GET a resource that doesn't exist, you can be sure to get a 404 error in a RESTful API. Contrast it with a non-RESTful API, which may return {error: "Not found"} wrapped in God knows how many layers. If you need the extra space to write a message to the developer on the other side, you can always use the body of the response.

Example

Imagine two APIs with the same functionality, one following REST and the other not. Now imagine the following clients for those APIs:

RESTful:

GET /products/1052/reviews
POST /products/1052/reviews       "5 stars"
DELETE /products/1052/reviews/10
GET /products/1052/reviews/10

HTTP:

GET /reviews?product_id=1052
POST /post_review?product_id=1052                  "5 stars"
POST /remove_review?product_id=1052&review_id=10
GET /reviews?product_id=1052&review=10

Now think of the following questions:

  • If the first call of each client worked, how sure can you be the rest will work too?

  • There was a major update to the API that may or may not have changed those access points. How much of the docs will you have to re-read?

  • Can you predict the return of the last query?

  • You have to edit the review posted (before deleting it). Can you do so without checking the docs?

Dehumidify answered 9/8, 2013 at 21:19 Comment(2)
This is not supposed to be an exhaustive list and contains only very practical advantages.Dehumidify
This is a very smart answer, I applaud.Tailwind
C
10

I recommend taking a look at Ryan Tomayko's How I Explained REST to My Wife

Third party edit

Excerpt from the waybackmaschine link:

How about an example. You’re a teacher and want to manage students:

  • what classes they’re in,
  • what grades they’re getting,
  • emergency contacts,
  • information about the books you teach out of, etc.

If the systems are web-based, then there’s probably a URL for each of the nouns involved here: student, teacher, class, book, room, etc. ... If there were a machine readable representation for each URL, then it would be trivial to latch new tools onto the system because all of that information would be consumable in a standard way. ... you could build a country-wide system that was able to talk to each of the individual school systems to collect testing scores.

Each of the systems would get information from each other using a simple HTTP GET. If one system needs to add something to another system, it would use an HTTP POST. If a system wants to update something in another system, it uses an HTTP PUT. The only thing left to figure out is what the data should look like.

Coffeehouse answered 3/2, 2010 at 10:7 Comment(8)
Wife: Is this another robot thing?Longshoreman
This is a nice text, but it didn't give any examples of why it would be bad to use GET and POST for everything.Slemmer
@dimitri it's not bad, it's just that restful is betterCoffeehouse
That's why I try to discover why it is better :-)Slemmer
You can use GET and POST and still not violate any REST constraints. You don't need to use DELETE. e.g. Can you guess what the following request does POST /Trashcan?url=/document/247 I am not violating any REST constraint by doing this. The uniform interface constraint says that when you use a verb it must do what the spec says it does. It does not imply that it is required to use all of the verbs, or even that if there is a more appropriate verb that you must use it.Reportorial
The writing has been taken down.Pothole
@Pothole waybackmachineBandage
The link for explaining to the wife is broken...but someone uploaded a version of it here looah.com/source/view/2284Gentile
D
5

I would suggest everybody, who is looking for an answer to this question, go through this "slideshow".

I couldn't understand what REST is and why it is so cool, its pros and cons, differences from SOAP - but this slideshow was so brilliant and easy to understand, so it is much more clear to me now, than before.

Daniels answered 3/1, 2013 at 7:44 Comment(0)
W
3

Caching.

There are other more in depth benefits of REST which revolve around evolve-ability via loose coupling and hypertext, but caching mechanisms are the main reason you should care about RESTful HTTP.

Waldack answered 3/2, 2010 at 16:23 Comment(5)
Can you give an example what might be cached and why the caching wouldn't happen with a non-REST solution?Slemmer
@Dimitri C.: A link wikipedia.org/article?id=19 wouldnt be cached by a proxy, since it ignore parameters passed in the url. In the other hand a link wikipedia.org/REST would be cached, understood?Metallurgy
If caching was the main benefit of REST, I can assure you that I would not have spent the last two years building RESTful services.Reportorial
Darrel, you might be building systems that are at a scale of distribution in which loose coupling is of the highest importance (interested to know what type of systems these are), but most people aren't - or they're using technologies (i.e. browsers and html) in which a large majority of the hard work is done for them.Waldack
So why not just use GET /get_article/19/ and POST /update_article if caching is your concern. You can still do everything with just GET and POST and I believe REST means "Use GET, POST, PUT and DELETE only." and not just "Don't use query strings." so what I suggested wouldn't be REST. Then again, nobody can really agree what REST is so I'm putting it in a bucket with "Web 2.0".Whoosh
P
3

It's written down in the Fielding dissertation. But if you don't want to read a lot:

  • increased scalability (due to stateless, cache and layered system constraints)
  • decoupled client and server (due to stateless and uniform interface constraints)
    • reusable clients (client can use general REST browsers and RDF semantics to decide which link to follow and how to display the results)
    • non breaking clients (clients break only by application specific semantics changes, because they use the semantics instead of some API specific knowledge)
Patronizing answered 10/9, 2014 at 2:45 Comment(0)
M
0
  • Give every “resource” an ID
  • Link things together
  • Use standard methods
  • Resources with multiple representations
  • Communicate statelessly

It is possible to do everything just with POST and GET? Yes, is it the best approach? No, why? because we have standards methods. If you think again, it would be possible to do everything using just GET.. so why should we even bother do use POST? Because of the standards!

For example, today thinking about a MVC model, you can limit your application to respond just to specific kinds of verbs like POST, GET, PUT and DELETE. Even if under the hood everything is emulated to POST and GET, don't make sense to have different verbs for different actions?

Metallurgy answered 3/2, 2010 at 16:39 Comment(2)
"it would be possible to do everything using just GET": I already did some experiments with HTTP GET in Silverlight. My conclusion was that GET messages are considerably limited in size, whereas POST messages can be bigger (again: in the Silverlight setting). Therefore I'd choose to use HTTP POST for everything! :-)Slemmer
both solutions are against the standards. Do everything via POST isn't good, specially for queries. Note that in the last years all search engines that used to work as GET works now as GET. Why? because the “get” method has this ability to get spidered...Metallurgy
V
0

Discovery is far easier in REST. We have WADL documents (similar to WSDL in traditional webservices) that will help you to advertise your service to the world. You can use UDDI discoveries as well. With traditional HTTP POST and GET people may not know your message request and response schemas to call you.

Vassar answered 22/12, 2011 at 3:13 Comment(3)
Describing a RESTful web service with a WADL document defeats one of the main advantages of REST, in particular, all advantages gained from hypermedia.Noach
@ThomasEizinger Is a WADL really such a bad thing? Currently we are working with another company that has not provided a WADL on top it returns json-objects depending on what our request contains. I assume that WADL would be helpfull to clear thinks up.Woehick
WADL does a great job at describing an HTTP API, because that is what it was designed for. Depending on the service this company provides, a WADL may or may not be a good idea. If the service does not take advantage of hypermedia and just serializes some objects into JSON, they should also provide a documentation (WADL, Swagger, etc ..) about how their service works and what it expects / returns. WADL per se is not bad at all, it is just not the right tool for a (truly) RESTful webservice.Noach
E
0

One advantage is that, we can non-sequentially process XML documents and unmarshal XML data from different sources like InputStream object, a URL, a DOM node...

Elamitic answered 5/2, 2013 at 21:18 Comment(0)
S
0

@Timmmm, about your edit :

GET /timeline_posts     // could return the N first posts, with links to fetch the next/previous N posts

This would dramatically reduce the number of calls

And nothing prevents you from designing a server that accepts HTTP parameters to denote the field values your clients may want...

But this is a detail.

Much more important is the fact that you did not mention huge advantages of the REST architectural style (much better scalability, due to server statelessness; much better availability, due to server statelessness also; much better use of the standard services, such as caching for instance, when using a REST architectural style; much lower coupling between client and server, due to the use of a uniform interface; etc. etc.)

As for your remark

"Not all actions easily map to CRUD (create, read/retrieve, update, delete)."

: an RDBMS uses a CRUD approach, too (SELECT/INSERT/DELETE/UPDATE), and there is always a way to represent and act upon a data model.

Regarding your sentence

"You may not even be dealing with object type resources"

: a RESTful design is, by essence, a simple design - but this does NOT mean that designing it is simple. Do you see the difference ? You'll have to think a lot about the concepts your application will represent and handle, what must be done by it, if you prefer, in order to represent this by means of resources. But if you do so, you will end up with a more simple and efficient design.

Scrounge answered 23/12, 2013 at 16:51 Comment(0)
S
-1

Query-strings can be ignored by search engines.

Scorify answered 3/2, 2010 at 9:58 Comment(4)
Using query string is totally RESTful.Pail
Dimitri, some search engines ignore dynamic links. Not so much any more, but it's still frowned upon. If you run a small site, then googlebot might not index all your pages if they have a question mark in the path.Scorify
...which is just plainly false, when you mention Google: googlewebmastercentral.blogspot.com/2008/09/…Tabbitha
-1 for Query-strings is not ignored by search engines. webmasters.googleblog.com/2008/09/…Tallyho

© 2022 - 2024 — McMap. All rights reserved.