2438

I'm developing a new RESTful webservice for our application.

When doing a GET on certain entities, clients can request the contents of the entity. If they want to add some parameters (for example sorting a list) they can add these parameters in the query string.

Alternatively I want people to be able to specify these parameters in the request body. HTTP/1.1 does not seem to explicitly forbid this. This will allow them to specify more information, might make it easier to specify complex XML requests.

My questions:

  • Is this a good idea altogether?
  • Will HTTP clients have issues with using request bodies within a GET request?

http://tools.ietf.org/html/rfc2616

Honey
  • 24,125
  • 14
  • 123
  • 212
Evert
  • 75,014
  • 17
  • 95
  • 156
  • 574
    The advantage is that allows easily sending XML or JSON request bodies, it doesn't have a length restriction and it's easier to encode (UTF-8). – Evert Jun 10 '09 at 21:51
  • 32
    If what you're after is a safe and idempotent method that allows request bodies, you may want to look at SEARCH, PROPFIND and REPORT. Of course not using GET and having a request body defeats caching more or less. – Julian Reschke Dec 06 '11 at 09:33
  • 3
    Whatever about whether the spec allows it, it goes against the very spirit of REST. – Jon Hanna Aug 17 '12 at 21:38
  • 3
    good luck with clients implementing request methods like SEARCH. You're much more likely to be able to do GET + Body. But Fiddler for one doesn't allow it, though most browser will (or have in the past) – fijiaaron Aug 30 '12 at 21:15
  • 257
    @fijiaaron: It's 3 years later, and since then I've gotten extensive experience writing webservices. It's basically all I have been doing for the last few years. I can safely say, it is indeed a very bad idea to add a body to a GET request. The top two answers stand like a rock. – Evert Aug 31 '12 at 00:34
  • 1
    I agree. It can be done if you control everything from client to server (but then why do you need a webservice). But if that's what someone wants, they can do it, and rather than say something can't be done, we can explain the pitfalls. I've run into similar problems and the best answer I've come up with is to use POST, and just don't tell Roy Fielding because it will make him cry. – fijiaaron Sep 01 '12 at 16:40
  • @fijiaaron: can't speak for him, but I would doubt that he would think pure REST is the be all and end-all. Pick the right tool for the job. He does seem to care a great deal about people mis-using the term REST though. – Evert Sep 01 '12 at 20:24
  • 1
    @Evert: Any chance you could share some details on the challenges you faced with GETs and sending content in the body? I'm writing my first API and I think I'm being lead down to using a GET + body approach. It'd be useful to have some real-world examples of some difficulties that were encountered and potential solutions. – Ellesedil May 01 '14 at 15:13
  • 29
    @Ellesedil: Simply put: Whatever advantages that exist to using GET over POST, exist because of how HTTP is designed. Those advantages no longer exist, when you violate the standard in this way. Therefore there's only one reason left to use GET + a request body instead of POST: Aesthetics. Don't sacrifice robust design over aesthetics. – Evert May 01 '14 at 16:24
  • 2
    This answer sums it up nicely by referring to the HTTP/1.1 spec - http://stackoverflow.com/a/15656853/244128 – maerics Aug 21 '14 at 14:36
  • 16
    To underline what Evert said: "it doesn't have a length restriction". If your GET with query parameters is breaking length restriction (of 2048), then what other choice is there other than to put the query string information in a json object, for example, in the body of the request. – Kieran Ryan May 17 '15 at 15:22
  • 1
    Chiming in, having recently built a Native Http Module in C++ for IIS8, I can say that OnReadEntity doesn't fire on Get Requests, only on posts, or I was having extreme difficulty getting to the body of a Get Request... – Ryan Mann Apr 03 '16 at 21:41
  • @Evert So in the end what do you end up doing? Encode JSON parameters as Base64? – beldaz Jul 15 '16 at 01:52
  • @JulianReschke Can you provide pointers to SEARCH etc.? They don't appear to be part of HTTP request methods (on wikipedia at least) – beldaz Jul 15 '16 at 02:02
  • 1
    @beldaz Wikipedia is irrelevant; see http://www.iana.org/assignments/http-methods/http-methods.xhtml – Julian Reschke Jul 15 '16 at 09:45
  • 2
    The OP has later expended his thoughts in an interesting [article](https://evertpot.com/dropbox-post-api/) that points to this very question. – Aurelio Jan 16 '19 at 11:52
  • 1
    @beldaz SEARCH is a WebDAV method. See RFC5323: [Web Distributed Authoring and Versioning (WebDAV) SEARCH](https://tools.ietf.org/html/rfc5323) – Suncat2000 Mar 12 '19 at 14:25
  • 8
    With advent of GDPR and what is allowed to be exposed (and thus logged) in the URL query, we had to rewrite our APIs to pass sensitive information in the request body and change GETs into POSTs. So, for example `GET http://host/customer?socialsecuritynumber={ssn}` became `POST http://host/customer/lookup` with the sensitive information sent in the body, which is excluded from external and internal logging – Stanislav Mar 18 '19 at 14:32

21 Answers21

2011

Roy Fielding's comment about including a body with a GET request.

Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.

So, yes, you can send a body with GET, and no, it is never useful to do so.

This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress).

....Roy

Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and changing your response based on its contents, then you are ignoring this recommendation in the HTTP/1.1 spec, section 4.3:

...if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

And the description of the GET method in the HTTP/1.1 spec, section 9.3:

The GET method means retrieve whatever information ([...]) is identified by the Request-URI.

which states that the request-body is not part of the identification of the resource in a GET request, only the request URI.

Update

The RFC2616 referenced as "HTTP/1.1 spec" is now obsolete. In 2014 it was replaced by RFCs 7230-7237. Quote "the message-body SHOULD be ignored when handling the request" has been deleted. It's now just "Request message framing is independent of method semantics, even if the method doesn't define any use for a message body" The 2nd quote "The GET method means retrieve whatever information ... is identified by the Request-URI" was deleted. - From a comment

From the HTTP 1.1 2014 Spec:

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

gagarwa
  • 979
  • 11
  • 21
Paul Morgan
  • 26,842
  • 3
  • 22
  • 27
  • 11
    Which server will ignore it? – fijiaaron Aug 30 '12 at 21:27
  • 1
    Any idea why this is part of the "server semantics for GET"? Is it some cacheing/proxying issue? – Sam Jul 17 '13 at 03:12
  • 89
    Caching / proxying are the two things you're most likely to break, yes. "Semantics" is just another way of saying "the way people who make other components will expect other components to operate". If you violate semantics, you're more likely to see things break in places where people wrote things that expected you to be honoring those semantics. – Stuart P. Bentley Aug 18 '13 at 01:33
  • 9
    It gives a headache when server silently ignores the body or any part of the request. Either it should parse it, or complain about it somehow. – Dmitri Zaitsev May 07 '14 at 07:45
  • Dmitri, I think ignoring it aligns with Jon Postel's advice to "Be liberal in what you accept" (RFC 1122). – Paul Morgan May 08 '14 at 13:21
  • For complicated search, maybe RESTful is not a suitable solution for you. I've tried developing my own protocol using POST requests exclusively. Every request contains one JSON body, with a top level directive in it. I have only one URL which accepts all requests, and then dispatches them to corresponding controllers according to that directive. – Aetherus Mar 17 '15 at 07:12
  • 1
    Aetherus, that can work but now you have routing detail in your body payload. That's a protocol that a client has to understand. IMHO you've complicated the interface for no benefit. – Paul Morgan Mar 17 '15 at 10:05
  • 135
    Elasticsearch is a fairly major product that utilises HTTP request bodies in GET. According to their manual whether a HTTP request should support having a body or not is undefined. I'm personally not comfortable with populating a GET request body, but they seem to have a different opinion and they must know what they're doing. https://www.elastic.co/guide/en/elasticsearch/guide/current/_empty_search.html – GordonM Oct 09 '15 at 16:22
  • 1
    @Sam From the HTTP/1.1 spec: *if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request*. The `GET` method specifies no semantics for request bodies, so servers SHOULD ignore them. – Emil Lundberg Dec 10 '15 at 10:52
  • 30
    @iwein giving GET request bodies meaning is in fact *not* a violation of the spec. [HTTP/1.1](https://tools.ietf.org/html/rfc2616#section-4.3) specifies that servers SHOULD ignore the body, but [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) specifies that implementers are allowed to ignore "SHOULD" clauses if they have good reason to do so. Rather, a client *does* violate the spec if it assumes that changing the GET body will *not* change the response. – Emil Lundberg Dec 10 '15 at 11:03
  • @EmilLundberg I think I understand your argument and while hard to debunk, it's conclusion contradicts with the given quote by Roy Fielding. I'd suggest an edit that uses 'not following' than 'violating' to avoid this discussion entirely. – iwein Dec 10 '15 at 12:56
  • 123
    The RFC2616 referenced as "HTTP/1.1 spec" is now obsolete. In 2014 it was replaced by RFCs 7230-7237. Quote "_the message-body SHOULD be ignored when handling the request_" has been [deleted](https://tools.ietf.org/html/rfc7230#section-3.3). It's now just "_Request message framing is independent of method semantics, even if the method doesn't define any use for a message body_" The 2nd quote "_The GET method means retrieve whatever information ... is identified by the Request-URI_" was [deleted](https://tools.ietf.org/html/rfc7231#section-4.3.1). So, I suggest to edit the answer @Jarl – Artem Nakonechny Nov 04 '16 at 21:47
  • 4
    @GordonM alas, clearly they don't. This answer is correct, it violates the semantics of the GET request to return a response based on any data in the request body. – Nicholas Shanks Jan 19 '17 at 16:52
  • 35
    I know that it's an old thread - I stumbled upon it. @Artem Nakonechny is technically right but the [new spec](https://tools.ietf.org/html/rfc7231#section-4.3.1) says *"A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request."* So it's still not a really good idea if can be avoided. – fastcatch Sep 29 '17 at 13:39
  • 3
    Fastcatch is correct, @Artem Nakonechny even when you are technically correct you can read the [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) saying that: **sending a payload body on a GET request might cause some existing implementations to reject the request** – Luis Armando Mar 23 '18 at 14:47
  • 4
    Let's say you want to get a list of entities in one call. (1,4,21, ... , 100027001). Well the max length of a URL and query string is 2083 characters. You can increase that on your server but clients might enforce it. So how are you supposed to execute your query? Easy, you call GET with the list of Ids in the body: GetByIds(List ids). Also, what if your URL parameter has a query string over-sized for any other reason? You should put the query string in the body of the GET call. If you look at the Odata spec, it can't be fully implemented without a GET with a body. – Rhyous Apr 12 '19 at 15:06
  • 5
    PostMan also recently started allow GET in the body for testing. – Rhyous Apr 12 '19 at 15:09
  • An interesting implication of this: https://blogs.dropbox.com/developers/2015/03/limitations-of-the-get-method-in-http/ – Anamika Modi May 20 '19 at 15:43
  • 6
    @LuisArmando The new RFC means that if you send an HTTP GET with a payload body to an old application, this can refuse your request if it follows the old RFC specifications. But if you are creating a new application and you follow the RFC 7231, the GET method can accept a payload body and this is fine. – Alessandro C Jul 08 '19 at 07:02
  • Anyone knows what CloudFlare does with GET body? – iElectric Aug 15 '19 at 10:15
  • 3
    I am reading these answers because of Elastic Search queries. I guess I am not the only one @GordonM – NewestStackOverflowUser Aug 30 '19 at 07:19
  • 4
    I disagree with `it is never useful to do so`. When I want to `Get` a resource I often need to supply parameters, a lot more then just an Id, so I always create a Request JSON object specific to my needs, and I always end up using `Post` instead of `Get` because of this. So I do a `Post` request to `Get` a resource (I know I know) – Luke T O'Brien Oct 02 '19 at 21:05
  • The alternative to being html liberal is strong contracts and committees which led to the WS standards and OSI stack ..which certainly did not get as the far more liberal http , Rest and tcp .. Data however is different you need to validate strongly when accepting / generating data but once created you need to accept it and best effort to be Robust. – user1496062 Nov 11 '19 at 04:12
  • 1
    So what's the recommendation? Is it within the best practices to pass a body with a get request? – Aditya Patil Mar 23 '20 at 16:46
  • 2
    @AdityaPatil I think the conclusion is that you CAN do it, even if you don't necessarily should. At worst you can just use a post instead. – MasterOfTwo Apr 02 '20 at 14:28
  • I agree with the comments, but what is the alternative? Use another HTTP instead, even though it's related to getting data from the server? – Lelo Jun 19 '20 at 15:09
  • 2
    I think the alternative is that you should prefer to use GET with uri/query params for retrieval and only use GET with a request body when/if you hit the limitations of doing that. Very rarely have I needed to do so. But even in that case, I would suggest that a GET with a request body is better than POST for retrieval. At least the GET accurately identifies the purpose of the request. – c.dunlap Oct 07 '20 at 13:32
  • `even though it's related to getting data from the server?` - The semantic purpose of GET is not an arbitrary read-only operation. It's getting a representation of the resource identified by the URI. If you need a body for a read operation, it just doesn't fit GET request semantics, because you are no longer just fetching the representation of the URI. You might like the up and coming `SEARCH` method though. – Evert Dec 10 '20 at 17:42
317

While you can do that, insofar as it isn't explicitly precluded by the HTTP specification, I would suggest avoiding it simply because people don't expect things to work that way. There are many phases in an HTTP request chain and while they "mostly" conform to the HTTP spec, the only thing you're assured is that they will behave as traditionally used by web browsers. (I'm thinking of things like transparent proxies, accelerators, A/V toolkits, etc.)

This is the spirit behind the Robustness Principle roughly "be liberal in what you accept, and conservative in what you send", you don't want to push the boundaries of a specification without good reason.

However, if you have a good reason, go for it.

caskey
  • 11,131
  • 2
  • 24
  • 27
  • 253
    The Robustness Principle is flawed. If you are liberal in what you accept, you will get crap, if you have any success in terms of adoption, just because you accept crap. That will make it harder for you to evolve your interface. Just look at HTML. That's the reboustness principle in action. – Evgeniy Berezovsky Aug 09 '11 at 01:43
  • 33
    I think the success and breadth of adoption (and abuse) of the protocols speaks to the value of the robustness principle. – caskey Aug 15 '11 at 03:46
  • 43
    Have you ever tried parsing real HTML? It's not feasible to implement it yourself, that's why almost everyone - including the really big players like Google (Chrome) and Apple (Safari), did not do it but relied on existing implementations (in the end they all relied on KDE's KHTML). That reuse is of course nice, but have you tried displaying html in a .net application? It's a nightmare, as you either have to embed an - unmanaged - IE (or similar) component, with its issues and crashes, or you use the available (on codeplex) managed component that doesn't even allow you to select text. – Evgeniy Berezovsky Sep 02 '11 at 14:10
  • The HTTP spec only 'allows' this insofar as it is not explicitly forbidden and any intermediate servers (e.g. proxies) are expected to retain message-body parts in requests they are forwarding. That said, it's still not something people would expect. PUT and POST exist to provide the correct semantic commands for those cases. – caskey Jan 26 '13 at 01:36
  • 1
    @AbhijeetPatel AJAX requests don't send body data along with a GET request, because the [W3C XMLHttpRequest specification](http://www.w3.org/TR/XMLHttpRequest/#the-send()-method) doesn't allow it (which is no explicit contradiction to the HTTP specification). – Torben Jun 27 '13 at 13:19
  • 9
    Not only does the HTTP spec allow body data with GET request, but this is also common practice: The popular ElasticSearch engine's _search API recommends GET requests with the query attached in a JSON body. As a concession to incomplete HTTP client implementations, it also allows POST requests here. – Christian Pietsch Oct 25 '13 at 11:52
  • 4
    @ChristianPietsch, it is common practice today. Four years ago it was not. While the spec explicitly allows a client to optionally include (MAY) an entity in a request (section 7), the meaning of MAY is defined in RFC2119 and a (crappy) proxy server could be spec compliant while stripping off entities in GET requests, specifically as long as it doesn't crash, it can provide 'reduced functionality' by forwarding the request headers and not the included entity. Likewise there are a host of rules about what version changes MUST/MAY/SHOULD be made when proxying among different protocol levels. – caskey Oct 28 '13 at 21:49
  • 2
    @user437899 The .NET Framework will throw an exception if you attempt to send a body with a GET request. – Sam Harwell Jan 23 '14 at 15:32
  • 2
    One could then argue that the .NET Framework implementation is incorrect. – floum Jul 20 '18 at 15:10
174

You will likely encounter problems if you ever try to take advantage of caching. Proxies are not going to look in the GET body to see if the parameters have an impact on the response.

Naman
  • 23,555
  • 22
  • 173
  • 290
Darrel Miller
  • 129,370
  • 30
  • 183
  • 235
  • 12
    Using ETag/Last-Modified header fields help in this way: when a "conditional GET" is used, the proxies/caches can act on this information. – jldupont Jan 15 '10 at 11:42
  • 3
    @jldupont Caches use the presence of validators to know whether a stale response can be re-validated, however, they are not used as part of the primary or secondary cache key. – Darrel Miller Mar 26 '14 at 14:42
  • 3
    You could fix that with a checksum of the body in a query parameter – Adrian May Jan 03 '20 at 14:33
80

Neither restclient nor REST console support this but curl does.

The HTTP specification says in section 4.3

A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests.

Section 5.1.1 redirects us to section 9.x for the various methods. None of them explicitly prohibit the inclusion of a message body. However...

Section 5.2 says

The exact resource identified by an Internet request is determined by examining both the Request-URI and the Host header field.

and Section 9.3 says

The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI.

Which together suggest that when processing a GET request, a server is not required to examine anything other that the Request-URI and Host header field.

In summary, the HTTP spec doesn't prevent you from sending a message-body with GET but there is sufficient ambiguity that it wouldn't surprise me if it was not supported by all servers.

Dave Durbin
  • 3,339
  • 18
  • 31
  • 2
    Paw also has the option to support GET requests with bodies but it must be enabled in the settings. – s.Daniel Jan 07 '15 at 18:14
  • "The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI." Then, is it technically illegal/wrong to have a GET endpoint that gets all entities? E.g. `GET /contacts/100/addresses` returns a collection of addresses for the person with `id=100`. – Josh M. Jul 07 '16 at 19:21
  • The rest-assured Java library for testing REST APIs does not support GET request with a body. Apache HttpClient doesn't support it either. – Paulo Merson Sep 05 '16 at 18:33
  • Django also supports parsing a GET body – Bruno Finger Mar 21 '19 at 12:13
71

Elasticsearch accepts GET requests with a body. It even seems that this is the preferred way: Elasticsearch guide

Some client libraries (like the Ruby driver) can log the cry command to stdout in development mode and it is using this syntax extensively.

Rodrirokr
  • 1,151
  • 12
  • 24
jlecour
  • 2,625
  • 1
  • 23
  • 21
  • 5
    Was wondering why Elasticsearch allows this. That means this query to count all documents with payload to a GET request `curl -XGET 'http://localhost:9200/_count?pretty' -d ' { "query": { "match_all": {} } }'` is equivalent to including the payload as `source` param: `curl -XGET 'http://localhost:9200/_count?pretty&source=%7B%22query%22%3A%7B%22match_all%22%3A%7B%7D%7D%7D'` – arun Dec 11 '14 at 14:31
  • 48
    Complex queries can hit the http header max length. – s.Daniel Jan 07 '15 at 17:45
  • 11
    It was reading the elasticsearch documentation that took me to this question as I thought it was considered bad practice to include a body – PatrickWalker Jan 19 '16 at 13:59
  • 1
    It doesn't even need to be a complex query. Even a simple scroll can return a very long scroll_id(in a cluster with many shards), which will lead to overrunning the maximum url length if added there. – Brent Hronik Jul 27 '16 at 19:49
  • 21
    Elasticsearch supports the same request using POST. They only chose to allow a body in a GET because they felt a GET is more semantically correct than a POST when it comes to querying data. Its funny that Elasticsearch is mentioned so much in this thread. I would not use one example (albeit from a popular product) as a reason to follow the practice. – DSO Jul 01 '17 at 20:11
36

You can either send a GET with a body or send a POST and give up RESTish religiosity (it's not so bad, 5 years ago there was only one member of that faith -- his comments linked above).

Neither are great decisions, but sending a GET body may prevent problems for some clients -- and some servers.

Doing a POST might have obstacles with some RESTish frameworks.

Julian Reschke suggested above using a non-standard HTTP header like "SEARCH" which could be an elegant solution, except that it's even less likely to be supported.

It might be most productive to list clients that can and cannot do each of the above.

Clients that cannot send a GET with body (that I know of):

  • XmlHTTPRequest Fiddler

Clients that can send a GET with body:

  • most browsers

Servers & libraries that can retrieve a body from GET:

  • Apache
  • PHP

Servers (and proxies) that strip a body from GET:

  • ?
fijiaaron
  • 4,297
  • 3
  • 32
  • 28
  • 2
    Squid 3.1.6 also strips GET bodies when Content-Length is 0 or not set, and otherwise sends back a HTTP 411 Length Required even though length is set – rkok Mar 06 '14 at 09:14
  • 2
    Fiddler will, but it warns you. – toddmo Aug 05 '15 at 21:44
  • Are you saying that a `SEARCH` method would possibly break along the way? If proxies don't understand a method, they are expected to pass it through as is, so I'm not too sure why you think it would break anything... – Alexis Wilke Dec 07 '18 at 20:03
  • @fijiaaron would love to see this list updated. I'm trying to find a library in nodeJS that allows this, so far none. – tinker Jan 26 '21 at 04:59
34

What you're trying to achieve has been done for a long time with a much more common method, and one that doesn't rely on using a payload with GET.

You can simply build your specific search mediatype, or if you want to be more RESTful, use something like OpenSearch, and POST the request to the URI the server instructed, say /search. The server can then generate the search result or build the final URI and redirect using a 303.

This has the advantage of following the traditional PRG method, helps cache intermediaries cache the results, etc.

That said, URIs are encoded anyway for anything that is not ASCII, and so are application/x-www-form-urlencoded and multipart/form-data. I'd recommend using this rather than creating yet another custom json format if your intention is to support ReSTful scenarios.

dat
  • 1,415
  • 1
  • 19
  • 24
SerialSeb
  • 6,549
  • 20
  • 28
  • 4
    *You can simply build your specific search mediatype* Could you elaborate? – Piotr Dobrogost Sep 28 '11 at 19:45
  • 2
    By that I was saying that you could create a media type called application/vnd.myCompany.search+json which would contain the kind of search template you want a client to issue, and the client could then send that as a POST. As I've highlighted, there's already a media type for that and it's called OpenSearch, reusing an existing media type should be chosen over the custom route when you can implement your scenario with existing standards. – SerialSeb Oct 03 '11 at 11:47
  • 17
    That's clever, but overly complex, and inefficient. Now you have to send a POST with your search criteria, get a URI as a response back from your POST, then send a GET with the search criteria URI to the server for it to the GET the criteria and send the result back to you. (Except that including a URI in a URI is technically impossible because you can't send something that can be up to 255 characters within something that can be no more than 255 characters -- so you have to use a partial identifer and your server then needs to know how to resolve the URI for your POSTed search criteria.) – fijiaaron Aug 30 '12 at 21:26
28

I put this question to the IETF HTTP WG. The comment from Roy Fielding (author of http/1.1 document in 1998) was that

"... an implementation would be broken to do anything other than to parse and discard that body if received"

RFC 7213 (HTTPbis) states:

"A payload within a GET request message has no defined semantics;"

It seems clear now that the intention was that semantic meaning on GET request bodies is prohibited, which means that the request body can't be used to affect the result.

There are proxies out there that will definitely break your request in various ways if you include a body on GET.

So in summary, don't do it.

Adrien
  • 915
  • 7
  • 11
24

Which server will ignore it? – fijiaaron Aug 30 '12 at 21:27

Google for instance is doing worse than ignoring it, it will consider it an error!

Try it yourself with a simple netcat:

$ netcat www.google.com 80
GET / HTTP/1.1
Host: www.google.com
Content-length: 6

1234

(the 1234 content is followed by CR-LF, so that is a total of 6 bytes)

and you will get:

HTTP/1.1 400 Bad Request
Server: GFE/2.0
(....)
Error 400 (Bad Request)
400. That’s an error.
Your client has issued a malformed or illegal request. That’s all we know.

You do also get 400 Bad Request from Bing, Apple, etc... which are served by AkamaiGhost.

So I wouldn't advise using GET requests with a body entity.

user941239
  • 707
  • 6
  • 5
  • 74
    This example is pointless because usually when people are going to add body to `GET` requests, it's because their own custom server are able to handle it. The question thus is whether the other "moving parts" (browsers, caches, etc) will work properly. – Pacerier Apr 19 '16 at 01:56
  • 9
    This is a bad requests because your payload isn't expected (or sensible) for a `GET` *on that particular endpoint* -- it has nothing to do with the use of `GET` in the general case. A random payload could break a `POST` just as easily, and return the same `400 Bad Request`, if the contents were not in a format that made sense in the context of the specific request. – Brent Bradburn Sep 22 '18 at 16:13
  • And not just *on that endpoint* as a whole, but rather *on that specific URL*. – Lawrence Dol Feb 05 '19 at 21:42
  • 2
    This is irrelevant because it's just Google's server implementation at that URL. So it makes no sense to the question – Joel Duckworth Apr 22 '19 at 23:21
  • for me it was useful, as i was trying to use firebase functions with a get request + body, and this error can be very cryptic and hard to understand. – scrimau Nov 05 '19 at 09:40
  • @Pacerier this might have been mostly true 4 years ago. Now that Google Cloud is more of a thing, more people are likely to run into Google's conventions. I deployed a "server of my own" to accept a GET request body. Deployed the containerized server through Google Cloud's Run service and the service returns a 400 for requests with a body even though the container returns a useful response when deployed locally. – chishaku Jul 09 '20 at 08:19
20

From RFC 2616, section 4.3, "Message Body":

A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

That is, servers should always read any provided request body from the network (check Content-Length or read a chunked body, etc). Also, proxies should forward any such request body they receive. Then, if the RFC defines semantics for the body for the given method, the server can actually use the request body in generating a response. However, if the RFC does not define semantics for the body, then the server should ignore it.

This is in line with the quote from Fielding above.

Section 9.3, "GET", describes the semantics of the GET method, and doesn't mention request bodies. Therefore, a server should ignore any request body it receives on a GET request.

izrik
  • 798
  • 1
  • 7
  • 17
  • [Section 9.5](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5), "POST", also doesn't mention request bodies, so this logic is flawed. – CarLuva Jun 20 '14 at 13:40
  • 10
    @CarLuva The POST section says "The POST method is used to request that the origin server accept the entity enclosed..." The [entity body](http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2) section says "The entity-body is obtained from the message-body..." Therefore, the POST section does mention message body, although indirectly by referencing the entity body which is carried by the message body of the POST request. – frederickf Aug 08 '14 at 23:14
11

According to XMLHttpRequest, it's not valid. From the standard:

4.5.6 The send() method

client . send([body = null])

Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD.

Throws an InvalidStateError exception if either state is not opened or the send() flag is set.

The send(body) method must run these steps:

  1. If state is not opened, throw an InvalidStateError exception.
  2. If the send() flag is set, throw an InvalidStateError exception.
  3. If the request method is GET or HEAD, set body to null.
  4. If body is null, go to the next step.

Although, I don't think it should because GET request might need big body content.

So, if you rely on XMLHttpRequest of a browser, it's likely it won't work.

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
Rafael Sales
  • 188
  • 3
  • 8
  • 1
    downvoted due to the fact that XMLHttpRequest is an implementation. It might not reflect the actual specification it is supposed to implement. – floum Jul 20 '18 at 15:01
  • 13
    Downvote above is wrong, if some implementations don't support sending a body with a GET, then that may be a reason not to do it, irrespective of the specification. I actually ran into this exact problem in a cross-platform product I'm working on - only the platform using XMLHttpRequest failed to send the get. – pjcard Oct 10 '18 at 10:29
9

If you really want to send cachable JSON/XML body to web application the only reasonable place to put your data is query string encoded with RFC4648: Base 64 Encoding with URL and Filename Safe Alphabet. Of course you could just urlencode JSON and put is in URL param's value, but Base64 gives smaller result. Keep in mind that there are URL size restrictions, see What is the maximum length of a URL in different browsers? .

You may think that Base64's padding = character may be bad for URL's param value, however it seems not - see this discussion: http://mail.python.org/pipermail/python-bugs-list/2007-February/037195.html . However you shouldn't put encoded data without param name because encoded string with padding will be interpreted as param key with empty value. I would use something like ?_b64=<encodeddata>.

Community
  • 1
  • 1
gertas
  • 15,733
  • 1
  • 69
  • 57
  • I think this is a pretty bad idea :) But if I were to do something like this, I would instead use a custom HTTP header (and make sure that I always send back Vary: in the response). – Evert Feb 18 '13 at 16:25
  • Bad or not but doable :) With data in header there is similar problem with data size, see http://stackoverflow.com/questions/686217/maximum-on-http-header-values . However thanks for mentioning `Vary` header, I wasn't aware of it's real potential. – gertas Feb 18 '13 at 21:36
7

You have a list of options which are far better than using a request body with GET.

Let' assume you have categories and items for each category. Both to be identified by an id ("catid" / "itemid" for the sake of this example). You want to sort according to another parameter "sortby" in a specific "order". You want to pass parameters for "sortby" and "order":

You can:

  1. Use query strings, e.g. example.com/category/{catid}/item/{itemid}?sortby=itemname&order=asc
  2. Use mod_rewrite (or similar) for paths: example.com/category/{catid}/item/{itemid}/{sortby}/{order}
  3. Use individual HTTP headers you pass with the request
  4. Use a different method, e.g. POST, to retrieve a resource.

All have their downsides, but are far better than using a GET with a body.

Xenonite
  • 1,383
  • 3
  • 18
  • 34
7

I wouldn't advise this, it goes against standard practices, and doesn't offer that much in return. You want to keep the body for content, not options.

cloudhead
  • 14,909
  • 6
  • 38
  • 35
5

I'm upset that REST as protocol doesn't support OOP and Get method is proof. As a solution, you can serialize your a DTO to JSON and then create a query string. On server side you'll able to deserialize the query string to the DTO.

Take a look on:

Message based approach can help you to solve Get method restriction. You'll able to send any DTO as with request body

Nelibur web service framework provides functionality which you can use

var client = new JsonServiceClient(Settings.Default.ServiceAddress);
var request = new GetClientRequest
    {
        Id = new Guid("2217239b0e-b35b-4d32-95c7-5db43e2bd573")
    };
var response = client.Get<GetClientRequest, ClientResponse>(request);

as you can see, the GetClientRequest was encoded to the following query string

http://localhost/clients/GetWithResponse?type=GetClientRequest&data=%7B%22Id%22:%2217239b0e-b35b-4d32-95c7-5db43e2bd573%22%7D
nomail
  • 626
  • 6
  • 21
GSerjo
  • 4,571
  • 1
  • 29
  • 49
  • 8
    You should just use POST. If there is a method name in the url, you are violating the fundamental rest design. This is RPC, use POST. – Evert Feb 10 '14 at 15:40
  • 3
    I don't think that is a big deal, we have more problems during development with RESTful url (i.e. orders/1). As for me, something wrong with Get method, it's incompatible with OOP. And who care how url is look like :) But with message based approach we can create stable remote interface and it's really important. P.S. it's not RPC, it's message based – GSerjo Feb 10 '14 at 17:41
  • 4
    I think you're missing the whole point of REST. When you say, who cares what the url looks like, well REST cares, a lot. And why would REST be compatible with OOP? – shmish111 Dec 18 '15 at 13:53
  • No, I didn't I just see a bit further – GSerjo Dec 18 '15 at 14:57
5

What about nonconforming base64 encoded headers? "SOMETHINGAPP-PARAMS:sdfSD45fdg45/aS"

Length restrictions hm. Can't you make your POST handling distinguish between the meanings? If you want simple parameters like sorting, I don't see why this would be a problem. I guess it's certainty you're worried about.

chaz
  • 479
  • 1
  • 7
  • 21
  • You can send any parameters you want with the `x-` prefix, any limits on the length of headers would entirely be a server arbitrary limit. – Chris Marisic Jun 02 '15 at 21:15
4

IMHO you could just send the JSON encoded (ie. encodeURIComponent) in the URL, this way you do not violate the HTTP specs and get your JSON to the server.

Jon49
  • 3,994
  • 2
  • 31
  • 66
EthraZa
  • 348
  • 4
  • 9
4

For example, it works with Curl, Apache and PHP.

PHP file:

<?php
echo $_SERVER['REQUEST_METHOD'] . PHP_EOL;
echo file_get_contents('php://input') . PHP_EOL;

Console command:

$ curl -X GET -H "Content-Type: application/json" -d '{"the": "body"}' 'http://localhost/test/get.php'

Output:

GET
{"the": "body"}
Nick
  • 8,381
  • 6
  • 50
  • 75
  • Fun experiment! PHP will only read in `$_POST` when the body is sent with a POST request and `application/x-www-form-urlencoded`. That means the body is ignored in a `GET` request. In this case: `$_GET` and `$_POST` are very misleading anyway at this point. So better use `php://input` – Martin Muzatko Dec 13 '18 at 14:49
2

I am using the Spring framework's RestTemplate in my client programme and, at the server-side, I defined a GET request with a Json body. My primary purpose is the same as yours: when the request has numerous parameters, putting them in the body seems tidier than putting them in the prolonged URI string. Yes?

But, sadly, it's not working! The server-side threw the following exception:

org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing...

But I am pretty sure the message body is correctly provided by my client code, so what's wrong?

I traced into the RestTemplate.exchange() method and found the following:

// SimpleClientHttpRequestFactory.class
public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
    ...
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        ...
        if (!"POST".equals(httpMethod) && !"PUT".equals(httpMethod) && !"PATCH".equals(httpMethod) && !"DELETE".equals(httpMethod)) {
            connection.setDoOutput(false);
        } else {
            connection.setDoOutput(true);
        }
        ...
    }
}

// SimpleBufferingClientHttpRequest.class
final class SimpleBufferingClientHttpRequest extends AbstractBufferingClientHttpRequest {
    ...
    protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
        ...
        if (this.connection.getDoOutput() && this.outputStreaming) {
            this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
        }

        this.connection.connect();
        if (this.connection.getDoOutput()) {
            FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
        } else {
            this.connection.getResponseCode();
        }
        ...
    }
}

Please notice that in the executeInternal() method, the input argument 'bufferedOutput' contains the message body provided by my code. I saw it through the debugger.

However, due to the prepareConnection(), the getDoOutput() in executeInternal() always returns false which, in turn, makes the bufferedOutput completely ignored! It's not copied into the output stream.

Consequently, my server programme received no message body and threw that exception.

This is an example about the RestTemplate of the Spring framework. The point is that, even if the message body is no longer forbidden by the HTTP spec, some client or server libraries or frameworks might still comply with the old spec and reject the message body from the GET request.

Zhou
  • 389
  • 2
  • 11
  • You're not reading the spec or the comments here correctly. Clients and servers dropping the request body _is_ within spec. Don't use GET request bodies. – Evert Nov 18 '19 at 22:24
  • 3
    @Evert I didn't read the comments correctly or you didn't? :) If you scroll up to Paul Morgan 's answer (the top hitting answer) and read the comments carefully, you will find this: "The RFC2616 referenced as "HTTP/1.1 spec" is now obsolete. In 2014 it was replaced by RFCs 7230-7237. Quote "the message-body SHOULD be ignored when handling the request" has been deleted. It's now just "Request message framing is independent of method semantics, even if the method doesn't define any use for a message body ... " – Zhou Nov 20 '19 at 10:45
  • 1
    @Evert Moreover, I was using the REST testing utility "rest-assured" to test my Spring-boot backend. Both rest-assured and Spring-boot server-side kept the Json body for GET request! Only the Sping-framework's RestTemplate drops the body from GET requests, so Spring-boot, rest-assured and RestTemplate, which is/are wrong? – Zhou Nov 20 '19 at 10:50
  • 2
    @Evert Last but not lease, I didn't urge people to use body in GET requests, on the contrary, I was suggesting NOT doing so by analyzing the source code of the Sping-framework's RestTemplate, so why did you down-vote my answer? – Zhou Nov 20 '19 at 10:54
  • I didn't downvote your answer. I'm just clarifying that any HTTP implementation dropping GET request *is* in spec. – Evert Nov 20 '19 at 12:03
  • 1
    @Evert Oops... my apologies, Evert. – Zhou Nov 20 '19 at 20:47
1

Even if a popular tool use this, as cited frequently on this page, I think it is still quite a bad idea, being too exotic, despite not forbidden by the spec.

Many intermediate infrastructures may just reject such requests.

By example, forget about using some of the available CDN in front of your web site, like this one:

If a viewer GET request includes a body, CloudFront returns an HTTP status code 403 (Forbidden) to the viewer.

And yes, your client libraries may also not support emitting such requests, as reported in this comment.

Frédéric
  • 8,372
  • 2
  • 51
  • 102
-4

Create a Requestfactory class

import java.net.URI;

import javax.annotation.PostConstruct;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RequestFactory {
    private RestTemplate restTemplate = new RestTemplate();

    @PostConstruct
    public void init() {
        this.restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestWithBodyFactory());
    }

    private static final class HttpComponentsClientHttpRequestWithBodyFactory extends HttpComponentsClientHttpRequestFactory {
        @Override
        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
            if (httpMethod == HttpMethod.GET) {
                return new HttpGetRequestWithEntity(uri);
            }
            return super.createHttpUriRequest(httpMethod, uri);
        }
    }

    private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {
        public HttpGetRequestWithEntity(final URI uri) {
            super.setURI(uri);
        }

        @Override
        public String getMethod() {
            return HttpMethod.GET.name();
        }
    }

    public RestTemplate getRestTemplate() {
        return restTemplate;
    }
}

and @Autowired where ever you require and use, Here is one sample code GET request with RequestBody

 @RestController
 @RequestMapping("/v1/API")
public class APIServiceController {
    
    @Autowired
    private RequestFactory requestFactory;
    

    @RequestMapping(method = RequestMethod.GET, path = "/getData")
    public ResponseEntity<APIResponse> getLicenses(@RequestBody APIRequest2 APIRequest){
        APIResponse response = new APIResponse();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Gson gson = new Gson();
        try {
            StringBuilder createPartUrl = new StringBuilder(PART_URL).append(PART_URL2);
            
            HttpEntity<String> entity = new HttpEntity<String>(gson.toJson(APIRequest),headers);
            ResponseEntity<APIResponse> storeViewResponse = requestFactory.getRestTemplate().exchange(createPartUrl.toString(), HttpMethod.GET, entity, APIResponse.class); //.getForObject(createLicenseUrl.toString(), APIResponse.class, entity);
    
            if(storeViewResponse.hasBody()) {
                response = storeViewResponse.getBody();
            }
            return new ResponseEntity<APIResponse>(response, HttpStatus.OK);
        }catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<APIResponse>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        
    }
}
Bhaskara Arani
  • 1,240
  • 1
  • 18
  • 40
  • 1
    Well, that's some code… but the question isn't asking for code. It's asking if it is a good idea (no) and if clients will have problems doing it (yes). – Quentin Oct 20 '20 at 09:09