Practising REST Part 3 – Some Tools

Spring MVC provides a lot of useful features for building a RESTful API.

Using Json With @RequestBody and @ResponseBody

@ResponseBody can automatically convert a domain object into JSON. @RequestBody can automatically convert a JSON into a domain object.

  @RequestMapping(value="/users", method=RequestMethod.GET)
  public @ResponseBody User getUser(
           @RequestParam(required=false) String email,
           @RequestParam(required=false) 
             String mobileNumber){
    //return User object with the specified email 
    //and/or phone number;
  }

  @RequestMapping(value="/users/{userId}", 
                             method=RequestMethod.POST)
  public @ResponseBody User updateUser(
                              @PathVariable String userId,
                              @RequestBody User user){
    //Update User object having that id with 
    //the one passed
  }

@RequestParam(required=false) means that the String parameter will not be required. This will allow both: “/users?email=dennis@yahoo.com” and “/users?mobileNumber=77777777” to be valid.

Dealing With DateTime

ISO-8601 is a standard for Date and Time and it makes sense for you to use that format for your API (i.e. your API accepts ISO-8601 dates and returns dates in that format).

@ResponseBody, however, by default returns java.util dates as timestamps. To change this so that it returns ISO-8601 dates, override configureMessageConverters(List<HttpMessageConverter<?>> converters) and turn off WRITE_DATES_AS_TIMESTAMPS.

In your web configuration class:


  import com.fasterxml.jackson.databind.ObjectMapper;
  import org.springframework.http.converter.HttpMessageConverter;
  import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

  @Override
  public void configureMessageConverters(
                    List<HttpMessageConverter<?>> converters){
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(
      com.fasterxml.jackson.databind.SerializationFeature
      .WRITE_DATES_AS_TIMESTAMPS, false);
    converters.add(
       new MappingJackson2HttpMessageConverter(objectMapper));
  }

MapStruct

MapStruct is another useful tool. (Not from or part of Spring). Sometimes you want to return a version of your domain object that you’ve created purposely for transfer of data (Data Transfer Object). MapStruct is a very useful tool for that.

Leave a comment