Saturday, September 1, 2012

Returning a partial response in a JAX-RS web service - Part 2

See Part 1 of this blog post for background and reasoning for providing partial response in your JAX-RS API.

Here's the basic steps:
  1. A custom Apache CXF RequestHandler filter inspects each Request to look for a 'fields' Query Parameter.
  2. When the 'fields' parameter is found and has a value, we make sure the requested fields are initialized by Hibernate.
  3. Lastly, we use a Jackson ObjectWriter to apply a Jackson filter to the object and then build and return a Response with the resulting JSON.
Here's a link  to the ResponseFilter I'm using in my sample project in Github.

First we inspect the Request and make sure it is a Get, the request succeeded (200 OK), has a JSON response type, and indeed has 'fields' query parameter and corresponding value.

At this point let's make sure any requested lazy loaded fields get initialized.  I'm sure there's a better way of doing the next part.

The code that initializes the fields is beyond scope of this post but here's a link to the class in my Github repo in case you are interested.

Lastly, let's apply the Jackson filter and build the response. Notice we are adding "apiFilter" to the SimpleFilterProvider. Your entity classes will need to be annotated with @JsonFilter("apiFilter") and your CustomObjectMapper should be configured with filterProvider.setFailOnUnknownId(false);

Any reader comments, questions, and suggestions are appreciated. Thanks!

1 comment:

  1. Hi justin, the code your pointing at on github looks obsolete (404). I can't find it anymore.