对于Restful API,GET方法可以使用json数据吗? [英] For Restful API, can GET method use json data?
问题描述
我不想在URI中看到这么长的参数字符串.那么,GET方法可以使用json数据吗?
I don't want to see so long parameters string in the URI. So, can GET method use json data?
在我的情况下,我需要过滤给定类型的参数的结果.如果有很多参数,则长度可能超过URI的限制.那么,有没有针对此问题的最佳实践?
In my situation, I need to filter the result given kind of parameters. If there are a lot of parameter, the length may exceed the limit of URI. So, is there best practice for this problem?
推荐答案
从理论上讲,没有什么可以阻止您在GET
请求中发送请求正文. HTTP协议允许它,但是没有定义的语义,因此由您来决定当客户端发送GET
有效负载时将要发生的情况.例如,您必须定义JSON正文中的参数是否等效于querystring参数或完全等同于其他内容.
In theory, there's nothing preventing you from sending a request body in a GET
request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET
payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.
但是,由于没有明确定义的语义,因此无法保证应用程序和客户端之间的实现会尊重它.服务器或代理可能会拒绝整个请求,或者忽略正文或其他任何内容. REST处理失败的实现的方法是以与您的应用程序分离的方式来规避它,因此我想您有两个可以视为最佳实践的选择.
However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.
简单的选择是使用POST
代替其他答案建议的GET
.由于POST
尚未通过HTTP进行标准化,因此您必须记录一下它应该如何工作.
The simple option is to use POST
instead of GET
as recommended by other answers. Since POST
is not standardized by HTTP, you'll have to document how exactly that's supposed to work.
我更喜欢的另一种选择是,假设GET
有效负载从未被篡改,则可以实现您的应用程序.然后,万一某个实现的实现被破坏,您可以允许客户端使用X-HTTP-Method-Override
覆盖HTTP方法,这是客户端使用POST
模拟HTTP方法的一种流行约定.因此,如果客户端的实现中断,它可以将GET
请求编写为POST
,发送X-HTTP-Method-Override: GET
方法,并且您可以拥有一个与应用程序实现分离的中间件,并相应地重写该方法.如果您是纯粹主义者,这是最佳选择.
Another option, which I prefer, is to implement your application assuming the GET
payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override
, which is a popular convention for clients to emulate HTTP methods with POST
. So, if a client has a broken implementation, it can write the GET
request as a POST
, sending the X-HTTP-Method-Override: GET
method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.
这篇关于对于Restful API,GET方法可以使用json数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!