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

2019-07-04 00:24发布

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?

标签: api rest search
2条回答
叛逆
2楼-- · 2019-07-04 00:59

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.

查看更多
▲ chillily
3楼-- · 2019-07-04 00:59

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.)

查看更多
登录 后发表回答