I developed a restful API using Spring boot and I'm trying to find out the best approach to implement a partial response result. For now my /user/{Id}
endpoint returns something like this:
{
"firstname": "Jhon",
"lastname": "Doe",
"address": "156 Proton street",
"username": "jhonDoe",
"email": "[email protected]",
"company": "Fiction corp"
}
What I want to achieve is to expose an endpoint with a request parameter fields where I can specify the attributes that I want to retrieve, so the endpoint will be somehting like /users/{id}/fields=firstname,lastname,company
and the result will be:
{
"firstname": "Jhon",
"lastname": "Doe",
"company": "Fiction corp"
}
I already made some research and found an article about Squiggle library, but they don't mention how this can be integrated with Spring boot, Also if there's any other library that doesn't have to treat only the serialization but generate a custom Query based on Spring data (repositories) to only retrieve the specified fields will be most welcomed.
Is there any solutions like this? Or someone already figured out how to configure Squiggle in their existing application?
After more experiments I found the simplest way to use Squiggly library with spring boot and spring web annotations in Controller. The only one thing you should do is to add configuration class as follows:
@Configuration
@ConditionalOnClass(ObjectMapper.class)
public class SquigglyAutoconfigure {
@Bean
public FilterRegistrationBean squigglyRequestFilter(ObjectMapper objectMapper) {
Squiggly.init(objectMapper, new RequestSquigglyContextProvider());
FilterRegistrationBean<SquigglyRequestFilter> filter = new FilterRegistrationBean<>();
filter.setFilter(new SquigglyRequestFilter());
filter.setOrder(1);
return filter;
}
}
And then when you add query param "fields" to any endpoint inside controller:
@RequestParam(name = "fields", required = false) String fields
You will have filtered responses. For example with this kind of response body:
{
"id": "ISSUE-1",
"issueSummary": "Dragons Need Fed",
"issueDetails": "I need my dragons fed pronto.",
"reporter": {
"firstName": "Daenerys",
"lastName": "Targaryen"
}
}
When you put a request with fields=id,reporter.firstName you will get:
{
"id": "ISSUE-1",
"reporter": {
"firstName": "Daenerys"
}
}
More examples with nested objects, collections and others: https://github.com/bohnman/squiggly-java#reference-object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With