REST vs JSON-RPC?

153,266

Solution 1

The fundamental problem with RPC is coupling. RPC clients become tightly coupled to service implementation in several ways and it becomes very hard to change service implementation without breaking clients:

  • Clients are required to know procedure names;
  • Procedure parameters order, types and count matters. It's not that easy to change procedure signatures(number of arguments, order of arguments, argument types etc...) on server side without breaking client implementations;
  • RPC style doesn't expose anything but procedure endpoints + procedure arguments. It's impossible for client to determine what can be done next.

On the other hand in REST style it's very easy to guide clients by including control information in representations(HTTP headers + representation). For example:

  • It's possible (and actually mandatory) to embed links annotated with link relation types which convey meanings of these URIs;
  • Client implementations do not need to depend on particular procedure names and arguments. Instead, clients depend on message formats. This creates possibility to use already implemented libraries for particular media formats (e.g. Atom, HTML, Collection+JSON, HAL etc...)
  • It's possible to easily change URIs without breaking clients as far as they only depend on registered (or domain specific) link relations;
  • It's possible to embed form-like structures in representations, giving clients the possibility to expose these descriptions as UI capabilities if the end user is human;
  • Support for caching is additional advantage;
  • Standardised status codes;

There are many more differences and advantages on the REST side.

Solution 2

I have explored the issue in some detail and decided that pure REST is way too limiting, and RPC is best, even though most of my apps are CRUD apps. If you stick to REST, you eventually are going to be scratching your head wondering how you can easily add another needed method to your API for some special purpose. In many cases, the only way to do that with REST is to create another controller for it, which may unduly complicate your program.

If you decide on RPC, the only difference is that you are explicitly specifying the verb as part of the URI, which is clear, consistent, less buggy, and really no trouble. Especially if you create an app that goes way beyond simple CRUD, RPC is the only way to go. I have another issue with RESTful purists: HTTP POST, GET, PUT, DELETE have definite meanings in HTTP which have been subverted by REST into meaning other things, simply because they fit most of the time - but not all of the time.

In programming, I have long ago found that trying to use one thing to mean two things is going to come around sometime and bite you. I like to have the ability to use POST for just about every action, because it provides the freedom to send and receive data as your method needs to do. You can't fit the whole world into CRUD.

Solution 3

First, HTTP-REST is a "representational state transfer" architecture. This implies a lot of interesting things:

  • Your API will be stateless and therefore much easier to design (it's really easy to forget a transition in a complex automaton), and to integrate with independent software parts.
  • You will be lead to design read methods as safe ones, which will be easy to cache, and to integrate.
  • You will be lead to design write methods as idempotent ones, which will deal much better with timeouts.

Second, HTTP-REST is fully compliant with HTTP (see "safe" and "idempotent" in the previous part), therefore you will be able to reuse HTTP libraries (existing for every existing language) and HTTP reverse proxies, which will give you the ability to implement advanced features (cache, authentication, compression, redirection, rewriting, logging, etc.) with zero line of code.

Last but not least, using HTTP as an RPC protocol is a huge error according to the designer of HTTP 1.1 (and inventor of REST): http://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_5_2

Solution 4

Great answers - just wanted to clarify on a some of the comments. JSON-RPC is quick and easy to consume, but as mentioned resources and parameters are tightly coupled and it tends to rely on verbs (api/deleteUser, api/addUser) using GET/ POST where-as REST provides loosely coupled resources (api/users) that in a HTTP REST API relies on several HTTP methods (GET, POST, PUT, PATCH, DELETE). REST is slightly harder for inexperienced developers to implement, but the style has become fairly common place now and it provides much more flexibility in the long-run (giving your API a longer life).

Along with not having tightly coupled resources, REST also allows you to avoid being committed to a single content-type- this means if your client needs to receive the data in XML, or JSON, or even YAML - if built into your system you could return any of those using the content-type/ accept headers.

This lets you keep your API flexible enough to support new content types OR client requirements.

But what truly separates REST from JSON-RPC is that it follows a series of carefully thought out constraints- ensuring architectural flexibility. These constraints include ensuring that the client and server are able to evolve independently of each other (you can make changes without messing up your client's application), the calls are stateless (state is represented through hypermedia), a uniform interface is provided for interactions, the API is developed on a layered system, and the response is cacheable by the client. There's also an optional constraint for providing code on demand.

However, with all of this said - MOST APIs are not RESTful (according to Fielding) as they do not incorporate hypermedia (embedded hypertext links in the response that help navigate the API). Most APIs you will find out there are REST-like in that they follow most of the concepts of REST, but ignore this constraint. However, more and more APIs are implementing this and it is becoming more of a main-stream practice.

This also gives you some flexibility as hypermedia driven APIs (such as Stormpath) direct the client to the URIs (meaning if something changes, in certain cases you can modify the URI without negative impact), where-as with RPC URIs are required to be static. With RPC, you will also need to extensively document these different URIs and explain how they work in relation to each other.

In general, I would say REST is the way to go if you want to build an extensible, flexible API that will be long-lived. For that reason, I would say it's the route to go 99% of the time.

Good luck, Mike

Solution 5

According to the Richardson maturity model, the question is not REST vs. RPC, but how much REST?

In this view, the compliance to REST standard can be classified in 4 levels.

  • level 0: think in terms of actions and parameters. As the article explains, this is essentially equivalent to JSON-RPC (the article explains it for XML-RPC, but same arguments hold for both).
  • level 1: think in terms of resources. Everything relevant to a resource belong to the same URL
  • level 2: use HTTP verbs
  • level 3: HATEOAS

According to the creator of REST standard, only level 3 services can be called RESTful. However, this is a metric of compliance, not quality. If you just want to call a remote function that does a calculation, it probably makes no sense to have relevant hypermedia links in the response, neither differentiation of behavior based on the HTTP verb used. So, a such call inherently tends to be more RPC-like. However, lower compliance level does not necessarily mean statefulness, or higher coupling. Probably, instead of thinking REST vs. RPC, you should use as much REST as possible, but no more. Do not twist your application just to fit with the RESTful compliance standards.

Share:
153,266

Related videos on Youtube

Ali Shakiba
Author by

Ali Shakiba

github.com/shakiba

Updated on July 08, 2022

Comments

  • Ali Shakiba
    Ali Shakiba almost 2 years

    I'm trying to chose between REST and JSON-RPC for developing an API for a web application. How do they compare?

    Update 2015: I have found REST easier to develop and use for an API which is served on Web/HTTP, because the existing and mature HTTP protocol which is understood by both client and server can be leveraged by the API. For example response codes, headers, queries, post bodies, caching and many other features can be used by the API without any additional effort or setup.

    • Landon Poch
      Landon Poch over 10 years
      REST is definitely the popular answer right now. I'm not convinced that it's always the right answer though. There could be an impedance mismatch between a resource-centric REST API and a problem domain that is inherently task or workflow based. If you find that you're having to do different types of PATCHes to the same resource or that certain tasks don't map to a specific resource, then you have to start to bend the REST paradigm. Do you use actions/commands as resources. Do you differentiate command types in the Content-Type header as parameters? Not sure there's a one-size-fits all answer.
    • dnault
      dnault about 10 years
      JSON-RPC is simple and consistent, a joy to use.
    • Manohar Reddy Poreddy
      Manohar Reddy Poreddy almost 9 years
      Its Aug 2015, I have implemented both client & server using REST, first 2 days was learning then I understood why it was popular. It was real joy once a small app is created, the client really has no work to remember various url path, the server on node.js & client in javascript shared same structure (url paths) to communicate. Wow! it was very swift, product got delivered in just 15 days, even writing from scratch. REST is the way go. Also note that Popular Apache CouchDB uses REST, a great database, are very proud they did in REST too. In simple, REST is RIGHT(correct) with clean interface.
    • Stathis Andronikos
      Stathis Andronikos almost 9 years
      It depends on the constraints you have or your primary goal. For example, if performance is a major aspect your way to go is JSON-RPC (e.g. High Performance Computing). If your primary goal is to be agnostic so as to provide a generic interface to be interpreted by others, your way to go is REST. If you want both goals, you have to include both protocols. Your needs define the solution.
    • Ali Shakiba
      Ali Shakiba almost 9 years
      @StathisAndronikos You are right, my main goal was ease of use and a good performance for web apps (not HPC).
    • etech
      etech over 7 years
      @AliShakiba I suggest looking into HATEOAS. It is one approach to using REST without being constrained by the static API that you have provided your client with. It is also a bridge towards the semantic web approach.
    • Wecherowski
      Wecherowski about 4 years
      what kills me in the whole API design discussion is that no one talks about the technical benefits. I've seen tons of discussions about the usability of URLs and about naming conventions (which obviously is also important) but no one's talking about things like scalability, cacheability, development time and TTM, maintainability etc.
    • Seer
      Seer over 3 years
      The only concerns there that are really relevant are development time and maintenance. REST is a complex, pretty much non-standardised solution which makes it difficult to develop in many ways. You can use standards, but you're still presented with a choice. Which standard(s) do you use? Solutions like gRPC don't have that issue, you can only implement it one way. Personally I'm trying out JSON-RPC 2.0 at the moment. It's easy to develop servers and clients when using HTTP as transport, and it takes away a lot of the pain of working with REST.
  • Notre
    Notre almost 11 years
    What do you mean by "it's mandatory to embed links annotated with link relation types which convey meanings.." ?
  • Centurion
    Centurion about 10 years
    "Clients are required to know procedure names" - that's not argument because with REST this name is hardcoded into the URI instead of passing as parameter. Otherwise server won't know which method it should perform.
  • Centurion
    Centurion about 10 years
    "It's not that easy to change procedure signatures ... on server side without breaking client implementations", this also is debatable. Both REST and JSON-RPC are not SOAP and don't have WSDL that describes existing web services and their types so that could be used for dynamic change at client side. So, either way if you change web service you have to change the client. Otherwise you need to go with SOAP.
  • ioseb
    ioseb about 10 years
    @Centurion if "with REST this name is hardcoded into the URI" and if this name is known to client this is not REST, nothing close to it. In REST only methods should be known to clients are that defined by underlying protocol.
  • ioseb
    ioseb about 10 years
    @Centurion "Both REST and JSON-RPC are not SOAP and don't have WSDL" it is not about WSDL, it is about how client consumes service. If client is hardcoded against procedure/method names in either way it means client is not implemented correctly. Client only needs to know protocol methods, semantics + additional semantics dictated by media types. Otherwise it is not REST.
  • Centurion
    Centurion about 10 years
    @ioseb Well, REST is mostly fitted for CRUD type of applications imho. And there's no magic - the client should know something in order to call and get correct results. And with REST, clean and directory structure-like URIs should be exposed (ibm.com/developerworks/webservices/library/ws-restful). That said client must know the underlaying structure. So if there's will be added totally new functionality (new table), or will need to add totally new offline synchronization web service, then client will have to know that. So, we are talking about very little flexibility in any case.
  • Centurion
    Centurion about 10 years
    I have coded dosen of apps and yet didn't see any flexible web services. If you change backend and web services than the client always needs to be refactored / updated to fit new requirements. And I have mentioned SOAP and because it has something that gives flexibility, like WSDL, so you can automate something and have more flexibility because you can get info about result set, datatypes and available web services. REST and others don't have that at all. So nor REST, nor JSON-RPC, nor other web service type will give you magic that would eliminate the need for manual client updating.
  • ioseb
    ioseb about 10 years
    @Centurion please, i'm not going to go deep in REST details but this what it is. Look at HTTP/URI/HTML/Browsers. Do we rewrite browsers each time when something changes on server? no. There are plenty of resources describing REST architectural style and its constraints(especially hypermedia constraint). Number of written apps by individual development can not measure qualities of REST unless all of them are RESTful.
  • ioseb
    ioseb about 10 years
    @Centurion "REST is mostly fitted for CRUD type of applications imho" in this sentence "IMHO" can not identify qualities of REST architectural style. There is only one authoritative source, Roy Fielding's dissertation. Either we understand and accept REST arch style without "IMHO"s or otherwise no discussion makes sense around it.
  • ioseb
    ioseb about 10 years
    @Centurion and btw, "clean" URIs? there is no difference between "/path/to/something" and "/8aQir" these URIs are 100% perfectly restful from the REST pov.
  • ioseb
    ioseb about 10 years
    @Centurion and those IBM examples are totally wrong. They scream RPC and this is one of the misleading understanding of REST. What IBM document describes is perfectly valid Web API(or HTTP API, or you name it) but it is far from being RESTful.
  • Centurion
    Centurion about 10 years
    @ioseb Agree, regarding Roy Fielding's dissertation, but it's too theoretical, and a lot of discussions is going on the web for a decade. Devs are trying to understand its benefits over adhoc or json-rpc websevices, and how it needs to be applied. I have defended a dissertation of my own, and perfectly know most of dissertations are two complicated for the practical adaptation. JSON-RPC has clean, lightweight and easy to understand specification. Do you know anything similar for REST? If no other practical sources exist then it means REST is left for manual interpretation.
  • Centurion
    Centurion about 10 years
    For me, my current team and previous teams, RESTful web services are for CRUD type applications. Regarding "Do we rewrite browsers each time when something changes on server?" - no, because browsers are just HTTP executors, they have nothing to do with business logic, that client program needs to implement (show screens, perform related stuff). It looks like we have started flame war, but in general I wish I would have another solid source for RESTfull web services with practical usage flow, with magical flexibility that you are referring to. Meanwhile a lot of statements are too vague.
  • ioseb
    ioseb about 10 years
    @Centurion as i said, REST qualities could not be measured by experiences of individual developers and their personal interpretations. REST is very well defined architectural style. There are other resources/books describing its benefits. I'm not advocating REST and am not going to advocate it. The main question was "REST vs JSON-RPC" and i precisely(almost) wrote differences in short message. How anyone uses REST, interprets REST, understands REST or in general architectural styles and architecture of the web, is out of my business and i'm not going to continue this argument further.
  • oxygen
    oxygen almost 10 years
    @ioseb "REST is very well defined architectural style." What? Where is the spec? JSON-RPC has a spec. REST doesn't. It's not even a defacto standard. It is nothing. It's a style, described on Wikipedia.
  • ioseb
    ioseb almost 10 years
    @Tiberiu-IonuțStan Yes, it is very well defined. It is an architectural style, it is not a protocol and does not need any specs. It is clearly defined in author's dissertation. JSON-RPC is not an arch style, it is a protocol.
  • nepdev
    nepdev over 9 years
    This answer shows the all-too usual misconception of what REST actually is. REST is definitely not just a mapping of CRUD to HTTP methods. The idea that it is a problem to "add another method" clearly indicates that REST is misunderstood as RPC over HTTP, which it is not at all. Try reading Roy Fieldings blog or his dissertation - Google will help you find it - you are not describing REST at all in your answer.
  • Bruce Patin
    Bruce Patin over 9 years
    I am a very practical person. All descriptions of REST that I have read clearly start with a mapping of CRUD to HTTP methods. More is allowed to be added theoretically, but in practicality, not. As an example, I recently wanted to implement PATCH for Android devices, but found that Android does not allow PATCH, so I used POST with an explicitly defined action to that effect in the URI. Basically, pure REST won't do the jobs that I require, so I use what works.
  • spinkus
    spinkus over 9 years
    So @BrucePatin, in your version "REST" you have a controller with four public methods that map 1 to 1 with GET|PUT|POST|DELETE? Some frameworks do that but that is not REST. HTTP verbs make vague abstract assertions about the semantics of a given request. You have to map your end points into those classes appropriately. GET could map to many different end points, so could the others. There is in fact no reason you can't implement REST-ful JSON-RPC over HTTP.
  • Bruce Patin
    Bruce Patin over 9 years
    There is a very good reason. I might want several dozen actions, and have already run into a common use (Android) that does not even support PATCH. That kills it cold. I would rather be consistent than have to deal with several exceptions to the rule. In general, I will now only use GET, POST and DELETE. PUT does not allow for the feedback I would want on an update operation. I am using POST for almost everything. Regarding caching, it has caused many problems by returning old data. Regarding putting parameters in POST, ASP.NET already handles it automatically from automatic JSON objects.
  • Patrick
    Patrick over 9 years
    PATCH is not a standard (only proposed) HTTP 1.1 method therefore standard HTTPUrlConncetion does not support it (this is not an android specific issue, its also in JDK). You can however use alternative http clients such as OKHttp which supports it (and also implements HttpURLConnection interface, so it can be easily replaced) so I cannot see how this is a dealbreaker.
  • RJB
    RJB over 9 years
    +1 for the authoritative, guy-who-should-know reference.... It's hard to argue for RPC over HTTP after that, without acknowledging it as a hack/work-around....
  • Agile Jedi
    Agile Jedi about 9 years
    You just referenced something from 2000. It's more a philosophical argument for REST versus RPC. Semantically and applying an RPC pattern you can easily consider the URI to be the "procedure" and the encoded parameters to be ...well...the parameters. Either pattern would work just fine over HTTP. Same with SOAP, RAILS or any other number of patterns/protocols that have been overlayed onto HTTP. It doesn't matter as long as you offer a consistent API that doesn't break it's contract.
  • Agile Jedi
    Agile Jedi about 9 years
    I believe the bickering over what REST really is only underscores your comments and highlights a major shortcoming of REST. Conceptually it's difficult to find two people who completely agree on what RESTful is. Anyway it doesn't matter because no service should go undocumented RPC or REST. If it's documented then the developer who uses it should have no problems.
  • S.D.
    S.D. over 8 years
    I'd rather say REST is a form of RPC. A very specific form. That has decided to use HTTP protocol as a transport and as a semantic scheme. HTTP's elegant scheme and popularity is being discussed as a "feature" or REST and a "shortcoming" of RPC. The question is "REST vs JSON RPC" not "HTTP vs RPC".
  • Panu
    Panu over 8 years
    This answer does not contain any proof of its claims. Actually for me it seems to be full of false claims. REST requires on to know the endpoint names and data formats, RCP requires on to know procedure names, arguments and stuff. So hard to see how one is more decoupled. Nothing prevents embedding form like structures in RPC style and so on. For lack of sources and because of the vague claims I down voted this answer. Sorry.
  • dnault
    dnault over 8 years
    It's great to find a kindred spirit! I'm working on something similar over here: github.com/dnault/therapi-json-rpc
  • idelvall
    idelvall over 8 years
    :) I'll look into it
  • idelvall
    idelvall over 8 years
    @S.D. agreed. "The question is REST vs JSON-RPC" . Moreover, if JSON-RPC is correctly implemented over HTTP the comparative shortens, since no HTTP arguments can be used. So what offers RPC and not JSON_RPC over HTTP? Semantics (for the good -interoperability- and the bad -very limiting- )
  • Alexey
    Alexey about 8 years
    Aurélien, could you justify, why REST is easier to integrate with independent software parts? To me, regardless if you use RESTful API or RPC, the client software need to know the format your API talks.
  • Aurélien Bénel
    Aurélien Bénel about 8 years
    @Alexey This argument was relative to statelessness. It is easier to integrate a coffee machine whose API is CREATE CUP, than another that would contain INSERT COIN, SELECT COFFEE, SELECT SUGAR, and START. In the second API, because it depends on the machine state, you have to be very careful with the sequence of procedure calls.
  • oxygen
    oxygen almost 8 years
    HTTP as a RPC protocol is REST. So your incorrect interpretation is shockingly the other way around.
  • Dave
    Dave over 7 years
    I think the point about Android not supporting patch should probably be edited into your post (to the first paragraph) as it will add weight and clarity to your well written answer.
  • Algy Taylor
    Algy Taylor over 7 years
    Agree with this. REST works well for CRUD APIs since you have the obvious POST/GET/PUT/DELETE [PoGPuD? ;)] mapping. However, if your API doesn't fit comfortably in to those verbs, JSON-RPC may be a good option since the verbs are just going to confuse matters. So yeah, who's using it and why is a big factor.
  • The Muffin Man
    The Muffin Man over 7 years
    you eventually are going to be scratching your head wondering how you can easily add another needed method to your API for some special purpose. Not if you actually took the time to understand REST. Your typical crud customers/1 that now needs to be able to update their email signature could use POST customers/1/signature. If you want to make a new controller for that be my guest, but the work on the backend is no different whether you do rpc or rest.
  • Bruce Patin
    Bruce Patin over 7 years
    I am not going to make my code logic stand on its head, redoing the routing, just to suit some idea of REST in which the action is no longer up front where it belongs.
  • João dos Reis
    João dos Reis over 7 years
    Exactly - REST is the kingdom of the nouns, JSON-RPC is verbs.
  • Peter Krauss
    Peter Krauss over 7 years
  • Mark Cidade
    Mark Cidade about 7 years
    REST is an architectural style and not protocol-dependant.
  • dtoux
    dtoux about 7 years
    You are right REST is architectural principle. However, its theoretical foundation was heavily influenced by HTTP protocol and despite the claim of universal applicability it found no practical application beyond web domain. So, it is safe to say that when somebody mentions REST they refer to web services and not the architectural principle.
  • Austin_Anderson
    Austin_Anderson almost 7 years
    it's not SLIGHTLY harder, but rather extremely more difficult. I've been trying to understand it for 4 months or so, and still don't have a good handle of how to write a service that doesn't devolve into a stateless RPC over http using json, And I'm still not convinced there's a real difference between "REST" and what I just said
  • Dennis
    Dennis over 6 years
    This answer made me realise the similarities between GraphQL and JSON-RPC and why GraphQL is becoming a popular choice for SPAs.
  • Dennis
    Dennis over 6 years
    Note it's not easy to make changes on server side without breaking client implementations regardless of JSON-RPC or REST. There are ways to improve this, such as consumer-driven contract tests, versioning, introducing append-only changes, and even preferring named parameters over positional as that can slightly reduce coupling. But otherwise this argument can't be used solely against JSON-RPC.
  • clt60
    clt60 over 6 years
    @Centurion Hm. Instead of writing zillion comments to someone's answer, maybe would be better to write an consistent answer yourself. Such comments without the "big picture" of your view are nearly pointless.
  • mjhm
    mjhm over 6 years
    +1 for levels 0, 1, and 2. However I've never seen a successful implementation of HATEOS, but have seen two miserably failed attempts.
  • alancalvitti
    alancalvitti about 5 years
    "It is hassle free for machines to parse" - I've seen plenty of broken JSON (eg unescaped quotes in payload)
  • Belfordz
    Belfordz about 5 years
    OpenRPC is the equivalent to OpenAPI/Swagger, but for JSON-RPC
  • Belfordz
    Belfordz about 5 years
    Check out OpenRPC, it should solve your need for "easy to write RPC services that are self-describing and interoperable"
  • Belfordz
    Belfordz about 5 years
    This is a very large over-simplification of the topic. Why, specifically, is it "Better by design"? JSON-RPC can be as simple or as complicated as you want, and so the argument of it being "better' for "a lot of parameters and complicated methods" is also false. It's no better or worse in this matter.
  • Adrian Liu
    Adrian Liu about 5 years
    It doesn't matter if the RPC uses JSON or protobuf or XML to serialize the data. The key point is the API as I said. I don't mean one is better than the other in all cases. But I do think the parameters and methods matter when you are choosing between the two implementations. If they are simple, RESTful API is well understood by most of the programmers and you can easily construct the http request. If they are complicated, RPC is more capable of expressing such APIs, and your IDE and compiler can help you with it.
  • egerardus
    egerardus over 4 years
    +1 additionally, your RPC messages can be delivered over different protocols (HTTP POST, websocket, SSE, raw TCP, etc) and can all be passed off to the exact same handling code without further translation, e.g. like adding RESTful headers to websocket messages (something I was horrified to see attempted recently)
  • Konrad Viltersten
    Konrad Viltersten over 3 years
    I can't see how the linked article implies the statement using HTTP as an RPC protocol is a huge error. I might be too dense to understand the text mass, though. Would you be able to elaborate, please? I get what REST and RPC is and I agree with the said statement. However, I'd like to understand the rationale to the claim.
  • Aurélien Bénel
    Aurélien Bénel over 3 years
    @KonradViltersten, you don't need to read the whole thesis chapter. Section 6.5.2 (which anchor is in the URI) is entitled "HTTP is not RPC". In just 9 sentences, the designer of HTTP states his own view on the matter. This is for reference, if you are OK with my explanation, you probably don't need to check the validity on my statement. But if you want to, you can.
  • teashark
    teashark over 2 years
    Its these kinds of arguments which lead me to describing the APIs I like to build as "HTTP'ish" instead of "RESTful". ugh 😒