springjson-api

How to model custom request params in Spring for JSON API?


I'm currently trying to model out the query parameter structure of JSON API and work it into my Spring Boot project. I'm going to focus on filters, sorting, pagination, and maybe field restriction.

I want to start with filtering first, so I'd like my REST endpoints to be able to handle JSON-API style URL requests like

GET /comments?filter[post]=1 HTTP/1.1

GET /comments?filter[post]=1,2 HTTP/1.1

GET /comments?filter[post]=1,2&filter[author]=12 HTTP/1.1

My plan is capture all JSON API specific query parameters in a top-level JsonApiParams object like:

public class JsonApiParams {
  private Filters filters;
  private Sorting sorting;
  private Paging paging;

  // getters, setters
}

And then model out Filters, Sorting, Paging as well. This JsonApiParams object will then be accepted as a request param in my @RestController endpoints like so:

@RequestMapping(value = {"/api/v1/{entity}"},
            method = RequestMethod.GET,
            produces = {"application/vnd.api+json"})
@ResponseBody
public JsonApiTopLevel jsonApiGetByEntity(@PathVariable String entity, JsonApiParams params) {
  // convert params to DB query
}

So, how should I model my JsonApiParams object to be able to handle requests like the ones above (e.g. /comments?filter[post]=1,2&filter[author]=12) ?


Solution

  • Fortunately, Spring out-of-the-box uses the bracket notation for Maps. I was able to format my URL query params like this /comments?filter[post]=1,2&filter[author]=12 with the following model:

    public class JsonApiParams {
        private Map<String, List<String>> filter;
        private List<String> sort;
        private Map<JsonApiPaginationKeys, Integer> page;
    
        // getters & setters
    }
    

    Then, in my case, I converted the filters to a QueryDSL Predicate, and the sort and page fields into a Spring Pageable request. Easy conversion and worked seamlessly.