JSON-RPC 与 JSON 补丁

JSON-RPC vs JSON Patch

有很多类似“REST vs smth”的比较(例如, vs JSON-RPC), but I also see many similarities between JSON-RPC and JSON Patch – 它们都指定了operation/method,values/parameters,并允许执行批处理请求。唯一我看到的区别是 JSON-RPC 还描述了带有 ID 和错误的响应格式,所以它看起来更成熟。但也许他们只是有不同的优缺点,不同的适用案例?

JSON-RPC (2.0) is indeed mostly mentioned as a REST alternative. (A look at the more general discussion, REST vs SOAP vs RPC might be due but this is a rabbit hole, seriously. Part of the problem is, people talking about different RESTs and RPCs and confuse them.) Historically, RPC systems often suffered from confounded dependences related to schema requirements, custom serializations, protocol restrictions, and complex RPC/function mappings. JSON-RPC tries to entangle dependencies, it does not want to be everything RPC for everybody but to stay relatively narrow in scope. It supports a small(er) set of commands, and is more opinionated on how to implement it. Nonetheless, it's a complete package, highly flexible, and used for complex APIs that struggle to map all operations to HTTP verbs。事件、通知和批处理操作等新功能使 JSON-RPC 非常通用,是各种项目的不错选择;这些添加对于基于操作的微服务特别有用。

JSON-Patch (RFC6902), arguably, tries to solve a single common problem of APIs, i.e. partial updates. Instead of PUTting or POSTing (potentially heavyweight) changes to a (historically) growing URL space, using query params to carry the semantics, or introducing other complexities, JSON Patch offers an atomic update request that patches your JSON using a series of "add", "remove", "replace", "move" and "copy" operations. To quote JSON 补丁 RFC 的作者之一,Mark Nottingham (IETF):

This has a bunch of advantages. Since it’s a generic format, you can write server- and client-side code once, and share it among a number of applications. You can do QA once, and make sure you get it right. Furthermore, your API will become less complex, because it has less URI conventions, leading to more flexibility and making it easier to approach for new developers. Using this approach will also make caches operate more correctly; since modifications to a resource will “travel” through its URL, rather than some other one, the right stored responses will get invalidated.

关于 JSON Merge Patch (RFC7396 也可以说类似的事情,它可以用于相同的目的,但更像 diff/patch,它只包含更改而不是使用变异操作。在这方面,JSON Merge Patch 比 JSON Patch 更简单但限制更多,例如您不能将键设置为 null(因为 null 表示删除),合并仅适用于对象 {..},数组 [..] 只能作为一个整体替换,并且合并永远不会失败,可能会导致副作用,因此不是事务性的。这使得 Merge Patch(过于)简单化并且对于某些实际应用程序不切实际。还有更多相关项目,如 JSON-Diffpatch 等,它们采用类似的方法。

总的来说,它们各有优缺点,none 适合每个人的用例。这真的取决于 what problems you want to solve with your APIs。 JSON-RPC 可以说更通用和更成熟,但是,JSON-Patch 也是一个不错的选择,特别是如果您控制通信的双方。