SB2055
SB2055

Reputation: 12902

Reasons not to use POST when searching via API endpoint?

I think the standard approach to RESTful searching is this:

GET /users?parameter1=value1&parameter2=value2&parameter3=value3&parameter4=value4

But I want to do something like this:

GET /users
# Request body:
{
    "parameter1": "value1",
    "parameter2": "value2",
    "parameter3": "value3",
    "parameter4": "value4"
}

Update: I can't use GET in the above manner because some devices to not respect body content of GET requests. So I would have to use POST instead.

Is RESTful religiosity the only reason that I shouldn't use POST to send JSON data to an /api/search endpoint, as opposed to using the URI?

Are there any technical and demonstrable dangers in using POST in this manner?

I'm aware that this is similar to the following:

How to design RESTful search/filtering?

But I'm asking something more specific: namely, what are some reasons that this would be a bad approach, other than "it doesn't fit convention".

Upvotes: 2

Views: 2793

Answers (1)

Darrel Miller
Darrel Miller

Reputation: 142202

You can use POST to do this. The HTTP spec does not prohibit it.

By using GET you are more accurately representing the characteristics of the request. If you use POST, an intermediary cannot tell that you are performing a safe, idempotent request, even though you are. That may limit the benefits you get from certain intermediaries. You will not be able to take advantage of a cached response by using POST.

If you feel the loss of those benefits do not outweigh the benefits you see to having a cleaner URI, then go-ahead and use POST.

I would suggest that you do not make a habit of using POST over GET for no valid reason, but where sending a body is useful, then do it.

Also realize that if 6 months down the road, you really wish you could cache the response to the search, then you can always change the server response to be a redirect where the client redirects with a GET that has the parameter encoded in the Location URI and then you can take advantage of cached results.

The important thing is you MUST NEVER use a Http method that conveys semantics that are not true. i.e. Never use a GET to do something unsafe. Never use PUT to do something that is not idempotent. However, POST does not constrain the request in anyway, so you could always use POST. Just be aware that intermediaries can't do much to help with POSTs.

Upvotes: 8

Related Questions