且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

REST API:请求正文为 JSON 还是纯 POST 数据?

更新时间:2023-02-17 20:00:33

POST、PUT、GET 都是 HTTP 动词,它们本身并不表示传输数据的格式,所以 没有POST 格式.这意味着您可以选择任何方式对数据进行编码.

POST, PUT, GET are all HTTP verbs and do not, in and of themselves, indicate a format for transferring the data, so there is no POST format. That means that you can encode the data in any way you choose.

现在,您决定采用哪种格式应该真正更多地取决于您的 API 通常将如何使用.如果主要是处理从 Web 浏览器提交的表单,那么使用表单域编码可能是最合理的做法,因为它使客户端的交互更容易.

Now, what format you decide to go with should really be more a matter of how your API will generally be used. If it will be primarily fielding form submits from a web browser, then using a form fields encoding is likely the most reasonable thing to do since it makes that interaction easier for the client.

另一方面,如果您主要是从 AJAX 调用接收 JSON 数据,那么接收 JSON 格式可能是有意义的.如果两者都做,就没有任何理由不能接受两种格式的数据.

On the other hand, if you are primarily going to be receiving JSON data from AJAX calls, then receiving a JSON format may make sense. If you will do both, there isn't any reason you can't accept data in both formats.

要考虑的另一个方面是您将要来回传递的数据结构的复杂性.表单编码(也类似于查询字符串编码)是一种键值结构,而 JSON(或 XML)允许更丰富的数据结构.

The other aspect to consider is the complexity of the data structures you will be passing back and forth. Form encoding (similar to query-string encoding as well) is a key-value structure, while JSON (or XML) allows for a much richer data structure.

最后,选择对您在服务器端和客户端最简单的方法(因为我假设您还将编写相关 API 的主要客户端使用者).简单性总是优于复杂性,直到您能明确地证明复杂性给您带来可衡量的好处.

In the end, go with whatever is simplest for both you on the server side, as well as you on the client side (since I assume you will also be writing the primary client consumer of the API in question). Simplicity is always preferred over complexity until you can definitively show that more complexity gives you a measurable benefit.

此外,我要提到的最后一件事是 REST 不仅仅是关于干净的 URL 或正确使用 HTTP 动词.这些方面真的只是锦上添花.REST 架构背后的核心思想是超文本是应用程序状态的引擎.通过简单地跟踪服务器响应中的 URL,一个好的客户端可以了解所有可用的操作,并且不需要知道除基本 URL 以外的任何信息.其他一切都可以从中发现.将其与定义明确的内容类型相结合,您将拥有一个世界,其中许多客户端可以与许多服务器进行通信,所有服务器都使用相同的语言",并且客户端无需任何了解服务器(或反之亦然),而不是基本 URL 和内容类型.这就是 REST 的全部内容.

Also, the last thing I will mention is that REST isn't just about clean URLs or using HTTP verbs correctly. Those aspects are really just icing on the cake. The core idea behind a REST architecture is that Hypertext is the engine of application state. By simply following URLs in the server responses, a good client can learn about all of the available actions and doesn't need to know anything more than the base URL. Everything else can be discovered from that. Couple that with well defined content types and you have a world where lots of clients can communicate with lots of servers, all speaking the same "language", and the clients don't need to know anything about the servers (or vice-versa) other than the base URL and the content types. That's what REST is all about.