对于 Restful API,GET 方法可以使用 json 数据吗? [英] For Restful API, can GET method use json data?

查看:59
本文介绍了对于 Restful API,GET 方法可以使用 json 数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不想在 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 正文中的参数是否等同于查询字符串参数或其他完全相同的参数.

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 方法,这是客户端使用 模拟 HTTP 方法的流行约定POST.因此,如果客户端的实现有问题,它可以将 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆