Filter API response json output based on query parameter

1.6k views Asked by At

I'm using Spring Data JPA and Spring Data Rest to expose my JPA entities as a webservice. My entities have several hundred attributes, and oneTo(very)Many relationships with other entities that have hundreds of attributes as well.

I'd like to be able for the user to pass in a query parameter that allows them to get back only the fields of the the JSON response body they are concerned with. In the past I've worked with IBM's Rational Team Concert REST API, and they allow the caller to pass in XPath query to select the fields they want returned. Their XPath integration also allowed the caller to apply filtering logic on the individual fields. For example, here is what was possible with that API:

workitem/workItem[creator/name='Bob Sacremento' or owner/name='Bob Sacremento']/(id|summary)

^The above query will return the id and the summary fields of all workItem elements whose owner or creator has a name equal to Bob Sacremento.

workitem/workItem/(id|summary|comments[creator/name='Bob Sacremento']/content)

^The above query will return the id, the summary and the comment contents fields of all workItem elements. But it will only show the comments that were created by Bob Sacremento.

I'd like to do something similar with my API. Before I wrote my own controllers to do so, I figured I'd ask if there is a framework that provides this functionality out of the box. It seems Spring Data REST does not.

2

There are 2 answers

0
glytching On

You can use Spring Data REST to define known projections, this can be used to create endpoints which expose specific projections on your underlying models and/or to allow invokers to request known (pre defined) projections via the URI e.g. foo/bar/bas?projection=summary.

More detais in the Spring Data REST docs.

However, I'm not aware of a library which will integrate with Spring Data REST, JPA and allow callers to specify projections (in the form of a SQL-esque SELECT statement for example) and then apply those projections on the fly on your behalf.

I suspect you'll need to define a query parameter such as select=a,b,c in your controllers and then use the supplied value to apply a projection via Spring Data JPA.

0
mancini0 On

GraphQl provides this functionality.