When implementing a REST API, you may want to provide flexibility for users about filtering the content based on their requests.

when requesting GET /movies/1

and when user sets fields, GET /movies/1?fields=year,subject,director the result would be

Implementation of this behavior is very similar to my previous tutorial about Role Based Content in Spring. I’m using the same sample project for this tutorial also.

We have this Movie entity.

And we have this movie controller.

We are injecting @AuthenticatedUser TutorialUser user (Check here for the details of this implemantation) and @RequestParam(value = "fields", defaultValue = raw) String rawFields to our controller method.

Since we’ll be doing variable filtering, the method is returning MappingJacksonValue. In getMappingJacksonValue method, comparing the variables coming with the fields parameter to the existing variable List of corresponding user role. Creating the String array for the matching variables and setting it as a filter and returning the result.

So this code is checking both user role and the fields in the request before generating the response content.

Since user/user has limited variable set, executing GET /movies/1?fields=actor,actress,year would result following json with only year in it.

If year is removed from request, GET /movies/1?fields=actor,actress the response would be

You can check the sample project at my github.

I’m using Postman when I want to play with the requests. Postman scripts for this application is here. You can just import and use them. But if you would like to use another tool, here is the api doc

user/pass = admin/admin and user/user

base url: http://localhost:8080
GET /movies // gets list of movies
GET /movies?fields=id,year… // return the specified fields in the list of movies
GET /movies/{id} //gets the movie with specified id
GET /movies/{id}?fields=id,year… // return the specified fields of the specified movie

POST /login?username=admin&password=admin

Have fun!