Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter API response json output based on query parameter

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.

like image 444
mancini0 Avatar asked Mar 24 '26 17:03

mancini0


1 Answers

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.

like image 99
glytching Avatar answered Mar 27 '26 07:03

glytching



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!