Pedro Borges Pedro Borges - 4 months ago 10
Java Question

REST best practise for retrieving a specific subset of elements

Ok, so we all know the REST way of getting a list of all entities would be to HTTP/GET

/entities
, the best way of getting a single entity would be to HTTP/GET
/entities/{entityId}
and the best way to get some entities is to HTTP/GET
/entities/{entityId}?where=condition
right?

But what would be a good approach when we need to get a specific set of entities, equivalent to a SQL
select ... where id in(id1, id2...)
when multiple HTTP/GET
entities/{entityId}
is not an option due to latency?

And specifically how would I be able to do it with RESTEasy

Answer

As per HTTP request type, each request type should serve as per protocol.

For example, HTTP/get should always be retrieving data and never do modifications using this call.

Also, as per REST, we should use these HTTP types as follows:

  1. GET - To retrieve entity.
  2. PUT - To save / update entity
  3. POST - To query or save entity
  4. DELETE - To remove entity

And so on ...

Hence, I would recomment to implement a /query endpoint of HTTP/post type which should be made generic to handle maximum query scenarios.

We could send nested json data in body to specify query parameters.

Json body for example:

    {
    "whereClause":{
    "OR":{
    {
    "field":"name",
    "operator":"=",
    "value":"Raj"
    },
    {
    "field":"age",
    "operator":">=",
    "value":20
    }
    },
"orderByClause":{
"name":"ASC"
"age":"DESC"
},
"groupByClause":[
"name"
]
    }

This way you would achieve high flexibility and may query is lots of different ways.

Hope it helps!!