HTTP GET with request body

Asked 2023-09-20 20:21:42 View 423,400

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?

https://www.rfc-editor.org/rfc/rfc2616

  • 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). - anyone
  • 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. - anyone
  • @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. - anyone
  • @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. - anyone
  • 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. - anyone

Answers

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.

Answered   2023-09-20 20:21:42

  • 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. - anyone
  • 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. elastic.co/guide/en/elasticsearch/guide/current/… - anyone
  • @iwein giving GET request bodies meaning is in fact not a violation of the spec. HTTP/1.1 specifies that servers SHOULD ignore the body, but RFC 2119 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. - anyone
  • 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. So, I suggest to edit the answer @Jarl - anyone
  • I know that it's an old thread - I stumbled upon it. @Artem Nakonechny is technically right but the new spec 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. - anyone

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.

Answered   2023-09-20 20:21:42

  • 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. - anyone
  • I think the success and breadth of adoption (and abuse) of the protocols speaks to the value of the robustness principle. - anyone
  • 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. - anyone
  • 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. - anyone
  • @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. - anyone

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.

Answered   2023-09-20 20:21:42

  • Using ETag/Last-Modified header fields help in this way: when a "conditional GET" is used, the proxies/caches can act on this information. - anyone
  • @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. - anyone
  • You could fix that with a checksum of the body in a query parameter - anyone
  • For caching just add hash of body to url! :) - anyone

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.

Answered   2023-09-20 20:21:42

  • 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' - anyone
  • Complex queries can hit the http header max length. - anyone
  • It was reading the elasticsearch documentation that took me to this question as I thought it was considered bad practice to include a body - anyone
  • 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. - anyone
  • 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. - anyone

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.

Answered   2023-09-20 20:21:42

  • Paw also has the option to support GET requests with bodies but it must be enabled in the settings. - anyone
  • "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. - anyone
  • The rest-assured Java library for testing REST APIs does not support GET request with a body. Apache HttpClient doesn't support it either. - anyone
  • Django also supports parsing a GET body - anyone
  • jmeter also does. - anyone

GET, with a body!?

Specification-wise you could, but, it's not a good idea to do so injudiciously, as we shall see.

RFC 7231 §4.3.1 states that a body "has no defined semantics", but that's not to say it is forbidden. If you attach a body to the request and what your server/app makes out of it is up to you. The RFC goes on to state that GET can be "a programmatic view on various database records". Obviously such view is many times tailored by a large number of input parameters, which are not always convenient or even safe to put in the query component of the request-target.

The good: I like the verbiage. It's clear that one read/get a resource without any observable side-effects on the server (the method is "safe"), and, the request can be repeated with the same intended effect regardless of the outcome of the first request (the method is "idempotent").

The bad: An early draft of HTTP/1.1 forbade GET to have a body, and - allegedly - some implementations will even up until today drop the body, ignore the body or reject the message. For example, a dumb HTTP cache may construct a cache key out of the request-target only, being oblivious to the presence or content of a body. An even dumber server could be so ignorant that it treats the body as a new request, which effectively is called "request smuggling" (which is the act of sending "a request to one device without the other device being aware of it" - source).

Due to what I believe is primarily a concern with inoperability amongst implementations, work in progress suggests to categorize a GET body as a "SHOULD NOT", "unless [the request] is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported" (emphasis mine).

The fix: There's a few hacks that can be employed for some of the problems with this approach. For example, body-unaware caches can indirectly become body-aware simply by appending a hash derived from the body to the query component, or disable caching altogether by responding a cache-control: no-cache header from the server.

Alas when it comes to the request chain, one is often not in control of- or even aware, of all present and future HTTP intermediaries and how they will deal with a GET body. That's why this approach must be considered generally unreliable.

But POST, is not idempotent!

POST is an alternative. The POST request usually includes a message body (just for the record, body is not a requirement, see RFC 7230 §3.3.2). The very first use case example from RFC 7231 (§4.3.3) is "providing a block of data [...] to a data-handling process". So just like GET with a body, what happens with the body on the back-end side is up to you.

The good: Perhaps a more common method to apply when one wish to send a request body, for whatever purpose, and so, will likely yield the least amount of noise from your team members (some may still falsely believe that POST must create a resource).

Also, what we often pass parameters to is a search function operating upon constantly evolving data, and a POST response is only cacheable if explicit freshness information is provided in the response.

The bad: POST requests are not defined as idempotent, leading to request retry hesitancy. For example, on page reload, browsers are unwilling to resubmit an HTML form without prompting the user with a nonreadable cryptic message.

The fix: Well, just because POST is not defined to be idempotent doesn't mean it mustn't be. Indeed, RFC 7230 §6.3.1 writes: "a user agent that knows (through design or configuration) that a POST request to a given resource is safe can repeat that request automatically". So, unless your client is an HTML form, this is probably not a real problem.

QUERY is the holy grail

There's a proposal for a new method QUERY which does define semantics for a message body and defines the method as idempotent. See this.

Edit: As a side-note, I stumbled into this StackOverflow question after having discovered a codebase where they solely used PUT requests for server-side search functions. This were their idea to include a body with parameters and also be idempotent. Alas the problem with PUT is that the request body has very precise semantics. Specifically, the PUT "requests that the state of the target resource be created or replaced with the state [in the body]" (RFC 7231 §4.3.4). Clearly, this excludes PUT as a viable option.

Answered   2023-09-20 20:21:42

  • GET bodies will is upgraded to a 'SHOULD NOT' in the next revision of the HTTP spec. No defined semantics does not mean 'you can decide what the semantics' are, it means in this case: 'it shouldn't alter the semantics of the request'. It's not on you that this is confusing, I think it was poorly written in the spec. The intent was that the presence of a body should not break implementations, nothing more. - anyone
  • I do not believe you or me can make any authoritative claims what "no defined semantics" mean. We can only take the specification at face value, and the spec could not give a well-defined meaning to the GET body, but was also smart enough to not forbid the body just because this limited set of authors at that time and place couldn't anticipate a use case. As I am sure both of us can agree to by now the practice does have at least one use case - thank you HTTP guys! - anyone
  • "legacy software written hundreds of years ago may drop the body or otherwise ignore it" — AFAIK this includes every current browser. - anyone
  • "Can you provide a reference please?" - httpwg.org/http-core/… - anyone
  • Thank you Evert! I read the article, very well written, and humorous! I don't think many people would disagree with you regarding why one should not include a GET body. But I still can not agree with statements like "body is obviously not allowed". Because it is obviously allowed lol. The quote you used yourself is spot on: "A client SHOULD NOT generate content in a GET request unless it is made directly to an origin server that has previously indicated, in or out of band, that such a request has a purpose and will be adequately supported". - anyone

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:

  • ?

Answered   2023-09-20 20:21:42

  • 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 - anyone
  • Fiddler will, but it warns you. - anyone
  • 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... - anyone
  • @fijiaaron would love to see this list updated. I'm trying to find a library in nodeJS that allows this, so far none. - anyone
  • @tinker Try fastify - anyone

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.

Answered   2023-09-20 20:21:42

  • You can simply build your specific search mediatype Could you elaborate? - anyone
  • 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. - anyone
  • 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.) - anyone

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 7231 (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.

Answered   2023-09-20 20:21:42

  • For a documented REST API, you may very well know that there are no proxies in between the client and server, and sending a JSON body may be a clearer API than encoding the same details in a query string. - anyone

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.

Answered   2023-09-20 20:21:42

  • Section 9.5, "POST", also doesn't mention request bodies, so this logic is flawed. - anyone
  • @CarLuva The POST section says "The POST method is used to request that the origin server accept the entity enclosed..." The entity body 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. - anyone

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.

Answered   2023-09-20 20:21:42

  • 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. - anyone
  • 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. - anyone
  • And not just on that endpoint as a whole, but rather on that specific URL. - anyone
  • This is irrelevant because it's just Google's server implementation at that URL. So it makes no sense to the question - anyone
  • @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. - anyone

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.

Answered   2023-09-20 20:21:42

  • downvoted due to the fact that XMLHttpRequest is an implementation. It might not reflect the actual specification it is supposed to implement. - anyone
  • 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. - anyone

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

Answered   2023-09-20 20:21:42

  • 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). - anyone
  • Bad or not but doable :) With data in header there is similar problem with data size, see stackoverflow.com/questions/686217/… . However thanks for mentioning Vary header, I wasn't aware of it's real potential. - anyone

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.

Answered   2023-09-20 20:21:42

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.

Answered   2023-09-20 20:21:42

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.

Answered   2023-09-20 20:21:42

  • 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. - anyone

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

Answered   2023-09-20 20:21:42

  • 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. - anyone
  • 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 - anyone
  • 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? - anyone
  • I don't see how REST could support or not support OOP. - anyone

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.

Answered   2023-09-20 20:21:42

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.

Answered   2023-09-20 20:21:42

  • yeah but the major issue is the length limit tho, how do we deal with it? - anyone
  • @Sebas I keep reading through all these answers wishing an answer would appear... - anyone

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"}

Answered   2023-09-20 20:21:42

  • 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 - anyone

If you want to allow a GET request with a body, a way is to support POST request with header "X-HTTP-Method-Override: GET". It is described here : https://en.wikipedia.org/wiki/List_of_HTTP_header_fields. This header means that while the method is POST, the request should be treated as if it is a GET. Body is allowed for POST, so you're sure nobody willl drop the payload of your GET requests.

This header is oftenly used to make PATCH or HEAD requests through some proxies that do not recognize those methods and replace them by GET (always fun to debug!).

Answered   2023-09-20 20:21:42

An idea on an old question:

Add the full content on the body, and a short hash of the body on the querystring, so caching won't be a problem (the hash will change if body content is changed) and you'll be able to send tons of data when needed :)

Answered   2023-09-20 20:21:42

  • Not really, there is a limitation on query string size in most of the clients and servers. - anyone
  • I meant a short hash on the querystring, and then the tons of data on the request body. So if the body data changes, the short hash on the querystring changes too and invalidates caches. - anyone

Sending data in the request body of GET API is not recommended by HTTP specification but there might be scenarios where using POST, PUT, or PATCH APIs are not suitable to use.

For instance, Elasticsearch sends a request body with GET API as the payload it is sent in the request body is quite complex and is not appropriate to send by query params in GET API.

But in most cases, we shouldn't send data in the request body with GET API as it is expected that there will be no request body in GET API and might be ignored by the API handling client.

Answered   2023-09-20 20:21:42

  • The fact that ElasticSearch does this doesn't mean anyone else should. It's still a bad idea. - anyone
  • Totally agrees with you. I am also of the opinion to not send the request body in GET API. That's what I have written in my answer. I just have explained that we can send (Just like Elasticsearch is using) but we shouldn't send the request body in GET API (As per HTTP specifications). - anyone

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);
        }
        
    }
}

Answered   2023-09-20 20:21:42

  • 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). - anyone
  • it is useful for me! - anyone