可以通过两种 HTTP 方法公开 REST api 吗? [英] Is it ok for a REST api to be exposed via two HTTP methods?

查看:42
本文介绍了可以通过两种 HTTP 方法公开 REST api 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我们有一个复杂的搜索 api 查询字符串,并希望让用户可以方便地使用 body.所以我们希望同时允许 GET 和 POST(或 PUT).

我知道会有一个关于搜索是只读操作的争论,根据 REST 标准它应该是 GET.据我了解,PUT 也不是缓存友好的.但我也知道有时偏离 REST 标准是可以的.但是为了客户的方便,有两种方法有意义吗?

解决方案

直接使用 POST 查询数据不是一件好事,正是因为你提到的原因.如果您的搜索字符串很复杂,也许您可​​以通过将查询过程分为两步来简化事情 - 一个涉及 POST,另一个涉及直接的 GET.>

第一步使用 POST 创建查询模板.查询字符串通过消息体发送,成为用户可以通过GET查询的新资源.查询字符串允许参数,类似于 SQL 查询.对查询的外观进行粗略的猜测,以下是一个示例:

(userName = $name) ||(createdBefore > $asOf && deleted=false)

您的用户将在消息正文中POST,并返回一个新的资源标识符.此资源将参数化视图"标识到您的数据中.假设此视图的资源 ID 是 aabb02kjh.现在您的用户可以这样查询:

https://app.yourserver.net/aabb02kjh?name=airboss&asof=20140101

这给您的 API 增加了一些复杂性,但它允许用户使用非常简单和标准的查询字符串定义和重用查询模板.

The problem is that we have a complex query string for a search api and want to let the users have convenience of using body instead. So we want to allow both GET and POST(or PUT).

I understand that there will be a debate of search being a read only operation and it should be GET only as per REST standards. Also PUT is not cache friendly as i understand. But i also know that its ok to deviate at times from the REST standards. But does it make sense to have two methods for client's convenience?

解决方案

Using POST directly to query data is not a good thing, precisely for the reasons that you mentioned. If your search string is complex, perhaps you could simplify things by splitting the querying process in two steps - one involving a POST, and another one involving straight GETs.

The first step creates a query template using the POST. The query string is sent via message body, and becomes a new resource that users can query through GET. Query string allows for parameters, in a way similar to SQL queries. Taking a wild guess at how your query might look, here is an example:

(userName = $name) || (createdBefore > $asOf && deleted=false)

Your users would POST this in a message body, and get a new resource identifier back. This resource identifies a parameterized "view" into your data. Let's say the resource id for this view is aabb02kjh. Now your users can query it like this:

https://app.yourserver.net/aabb02kjh?name=airboss&asof=20140101

This adds some complexity to your API, but it lets users define and reuse query templates with very simple and standard query strings.

这篇关于可以通过两种 HTTP 方法公开 REST api 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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