Clean and easy Android REST JSON API client with Spring REST Template and Jackson

September 22, 2014

While working on mobile applications at Handcrafted Mobile, we often use REST APIs, mostly in JSON or XML formats. As a software house, we’re often creating patterns, mechanism or libriaries that we can later re-use in next projects – here for example, most of Android, iOS or Windows Phone use backend APIs.

For recent Android project we’ve successfully used Spring Android REST Template with Jackson JSON parser, to have highly flexible REST client, allowing us to have non-standard configuration on HTTP connection level, and keep it easy to extend with new API methods. And all of that with only 2 Gradle dependencies:

compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'

In order to log in, our API required us to send user email and password in JSON-formatted request from Android device to ‘/session’ with POST. On success, it returned simple JSON with token field, containing token we should use for all future requests. As we are using Jackson in our project, we’ve created two classes: LoginRequest and TokenResponse to map both JSONs to java objects. Implementation of this endpoint is really simple – just a few lines of code:

public ApiResponse<TokenResponse> login(String email, String password) {
    LoginRequest requestObject = new LoginRequest();
    requestObject.email = email;
    requestObject.password = password;
    return processResponse(apiUrl() + "/session", HttpMethod.POST, requestObject, TokenResponse.class);
}

Of course, to have that nice API we need few more methods. We’ve packed all of them in ApiClient class:

  • processResponse() method creates ResponseExtractor, where Spring Android REST Template meets Jackson and response parsing is performed, handles basic errors and performs actual HTTP call
  • getRequestCallback() method, where request manipulation and stuff like settings headers can be performed
  • writeRequest() method, where requests are serialized to JSON format before sending them to the API
  • restTemplate() method, that creates underlying HttpClient factory & sets connection parameters

Full source code of this sample can be found on our GitHub account - https://github.com/codingfingers/Android-REST-API-Sample - you just need to write your own request and response classes and add new API calls implementations!

Posted by: Marcin Łępicki, https://github.com/mlepicki