Is it ok for a REST api to be exposed via two HTTP methods?

不羁的心 提交于 2019-12-13 14:33:14

问题


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?


回答1:


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.




回答2:


Interesting question. I mean by POST -> PUT,DELETE there are common workarounds for overriding HTTP methods:

  • sending a _method hidden input field with the post data
  • sending a _method query param in the URL
  • sending an X-HTTP-Method-Override header with the post

etc... So if they are valid (I am not sure about that), then you could use the same approach by GET as well.

According to REST constraints: cache and the uniform interface, and the HTTP method definitions, you have to use GET by retrieval requests. There are only a few URL query languages to make URLs readable, for example RQL, but you can always pick your favorite query language and serialize it for URL usage...

Another interesting approach to add link descriptions about the URL. (But that is very new for me either.)



来源:https://stackoverflow.com/questions/25766327/is-it-ok-for-a-rest-api-to-be-exposed-via-two-http-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!