REST request cannot be encoded for GET (URL too lo

2019-01-13 14:38发布

问题:

Example:

  • URL: http://example.com/collection/a%20search%20term

  • Method: GET

  • Response: All items in collection matching a search term.

Problem: The search term may be so long that it breaks the web server's maximum URL length.

How do I allow extremely long search terms and still stay RESTful?

回答1:

For inspiration, I just looked at Google Translate's API v2, which is "using the RESTful calling style."

Naturally, texts to be translated can be quite long. And so Google optionally allows sending a request with POST, but with a twist:

To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).

So it is possible to semantically transform a POST request into a GET request.

(This discovery led me to add the x-http-method-override tag to my question.)



回答2:

REST does not restrict POST to creation. Be careful with mapping CRUD to HTTP methods and assume that's RESTful. POST is the method used for any action that isn't standardized by HTTP.

Since the standard doesn't establish a limit for URIs, this can be considered a broken implementation, and it's ok to fix it. As long as the workaround is loosely coupled to your API, you are still RESTful. This means your API shouldn't implement a translation or override directly, but on a pre-processor of some kind that rewrites the request properly. It should be clearly documented somewhere that this is due to a broken implementation, and you expect it to eventually become obsolete.



回答3:

It's a bad smell if your query can be so long that it exceeds the maximum length (de facto for browsers is 2000 characters but it can be higher for other means of accessing REST APIs).

If the user can pass in that much data, it should go in the request body/data field, not in the URL.