REST API - GET Method with input parameter as JAVA Object in body

12,093

According to the specification of HTTP protocol with GET method no body can be supplied. E.g. you can pass data only as part of URI.

Actually, you can supply object via GET method. Just convert it into text (like JSON), encode it into base64 (because some symbols like spaces are not allowed in URI), put that content into input1 path variable (e.g. /URI/encodedpojohere). Then decode input1 string on server and convert it back to Java's POJO.

This approach has several limitations (the most obvious of them is limited length of URI string - something about 65535 symbols). And inefficiency (you cannot transmit arbitrary sequence of bytes and need to encode them). Perhaps, this is why there are not any standard convertors/annotations/helper classes for transmitting POJOs via GET request. So use POST or PUT methods instead. Spring and other frameworks have a bunch of utility classes/annotation for them.


Generally, it's possible to supply a body within HTTP GET method. Such approach was discussed there: HTTP GET with request body. Some well-known products, for example, Elasticsearch provides queries like this:

GET /bank/_search
{
  "query": { "match_all": {} }
}

(corresponding HTTP request can be executed via curl command line utility)

Anyway, HTTP GET with body is non-standard. Perhaps, this is why it's not supported in Java.

Share:
12,093
universe
Author by

universe

Updated on June 09, 2022

Comments

  • universe
    universe almost 2 years

    That's my current REST GET method.

    @GET
    @Path("/URI/{input1}")
    @Produces(MediaType.APPLICATION_JSON)
    public List<T> getDetails(@PathParam("input1") String input1) throws ServiceException;
    

    Now I want to add 3 more input parameters. Instead of adding all 4 parameters as pathparams, can I create a POJO object with all 4 input parameters and pass that POJO to GET method like this

    @GET
    @Path("/URI")
    @Produces(MediaType.APPLICATION_JSON)
    public List<T> getDetails(InputPojo input) throws ServiceException;
    

    POJO class with input parameters:

    class InputPojo {
        String input1;
        String input2;
        String input3;
        // Getters and Setters.
    }
    

    Or is this against REST GET specification and I cannot use Java POJO object as input parameter?