When you design search API for REST service there are multiple options technically available:
- use a GET with payload
- use a GET with URL query parameters
- use a POST with payload
In the previous post To be or not to be… I shared my thought about the first option (GET with body) which actually is only a technical option and definitely not the best choice.
So, let’s talk about the other two below.
When we think about the GET with URL query parameters usage we should remember all requested data is included in the URL and there is a restriction on size:
The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret.HTTP/1.1, 1999 (RFC 2616)
The good moment here is the most web servers have a quite big limit of 8192 bytes (8 Kb) for this case and this value usually configurable.
Also, when GET with URL query parameters is used there could be a URL size restriction in the browser, for example, this is the URL size limit in Chrome browser:
Chrome limits URLs to a maximum length of 2MB for practical reasons and to avoid causing denial-of-service problems in inter-process communication.Guidelines for URL Display (Chromium)
So, even considering all these restrictions in the general case there shouldn’t be any issue with the URL length.
But what if we replace GET with POST and put our request parameters into the request payload. Looks pretty good and without URL size limits now, but there are caveats as well:
…the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval. These methods ought to be considered “safe”. This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested.HTTP/1.1, 1999 (RFC 2616)
Methods can also have the property of “idempotence” in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property.HTTP/1.1, 1999 (RFC 2616)
Considering statements above GET which is “safe” and “idempotent” has an important benefit against POST – the cache mechanism support.
The response to a GET request is cacheable if and only if it meets the requirements for HTTP cachingHTTP/1.1, 1999 (RFC 2616)
As we can see, the usage of POST method for search provides mostly only one benefit – the size of the request payload.
So, comparing both options: GET with URL query parameters is preferable for search when POST with payload makes sense only in case of complex queries with tons of search parameters.
Even if you have a quite complex search logic there is still a chance to get it implemented in an elegant manner in GET with URL parameters form. For example, let’s see Google image search API:
Which is transformed into a short and elegant URL like below: