Search code examples
restapiget

HTTP GET request with body for RESTful API


I've been looking at how to implement the following:

I am developing a RESTful Web API (using .Net Core 2.2). I need to create an endpoint where the consuming client can send some text to the API, the API replaces some tokens in this text, and returns the text back to the consuming client.

I thought that the client should simply do a GET request, with the text in the body. The reply would then be the new text after the token replacements. However, from my research, it appears one should not stick anything with semantics in the body of a GET request. I'm not sure if arbitrary text with certain tokens that need to be replaced by the API qualifies as semantic? I've also seen it stated at "you should not be able to use the body of a GET request to alter the response". I guess I'm in trouble there, as depending what goes into he body, will affect the response.

So then, I've been struggling to figure out what is the correct way to do this. If anyone has an pointers I'd greatly appreciate it.

Thank you.


Solution

  • I thought that the client should simply do a GET request, with the text in the body. The reply would then be the new text after the token replacements. However, from my research, it appears one should not stick anything with semantics in the body of a GET request.

    Right - RFC 7231

    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.

    In basic HTTP, you've got choices. One is to include a representation of your document in the URI itself

    /?your_document_as_a_query_string
    /your/document/as/path/segments
    

    For short documents, that approach can be fine; but implementations are not required to support infinitely long identifiers, so you may discover that intermediate components reject your request, or crop the URI in transit.

    A safe mechanism for achieving your goal is to use POST, rather than GET. POST supports a message body, so you can send the blank form to the server, and receive back the edited version in the response.

    POST is the wildcard method of HTTP, it can mean anything. In the spec, the body of the response includes "a representation of the status of, or results obtained from, the action".

    You might also consider that the response duplicates a lot of the content of the body of the request, and consider instead the possibilities of fetching a map of your template values from the server, and then applying the template on the client.