Getting Started with Retrofit and Create an Android Client

retofit

Within this blog post we’re going through the basics of Retrofit and create an android client for API or HTTP requests.

However, this post doesn’t cover too much getting started information and what’s Retrofit about. For those information, please visit the projects homepage.

What is Retrofit

The official  Retrofit page describes itself as

A type-safe REST client for Android and Java.

You’ll use annotations to describe HTTP requests, URL parameter replacement and query parameter support is integrated by default. Additionally, it provides functionality for multipart request body and file uploads.

 

How to Declare (API) Requests

Please visit and read the API declaration section on the Retrofit homepage to understand and get a feeling of how to make requests. You’ll find all important information, clearly depicted with code examples.

 

Prepare Your Android Project

Now let’s get our hands dirty and back to the keyboard. If you already created your Android project, just go ahead and start from the next paragraph. Else, create a new project in your favorite IDE. We prefer Gradle as the build system, but you surely can use Maven as well.

 

Define Dependencies: Gradle or Maven

Now let’s set Retrofit as a dependency for your project. Select your used build system and define Refrofit and its dependencies in your pom.xml or build.gradle. When running the command to build your code, the build system will download and provide the library for your project. We propose to use Retrofit with OkHTTP which requires Okio to be defined as a dependency as well.

 

Retrofit 2

Use the following dependencies if you’re using Retrofit in version 2.

 

pom.xml

<dependency> 
 <groupId>com.squareup.retrofit2</groupId>
 <artifactId>retrofit</artifactId>
 <version>2.0.0</version>
</dependency> 
<dependency> 
 <groupId>com.squareup.retrofit2</groupId>
 <artifactId>converter-gson</artifactId>
 <version>2.0.0</version>
</dependency> 

 

build.gradle

dependencies { 
 // Retrofit & OkHttp
 compile 'com.squareup.retrofit2:retrofit:2.0.0'
 compile 'com.squareup.retrofit2:converter-gson:2.0.0'
}

Retrofit 2 by default leverages OkHttp as the networking layer and is built on top of it. You don’t need to explicitely define OkHttp as a dependency for your project, unless you have a specific version requirement.

Now that your project is ready to integrate Retrofit, let’s create a lasting Android API/HTTP client.

 

Sustainable Android Client

During the research for already existing Retrofit clients, the example repository of Bart Kiers came up. Actually, it’s an example for OAuth authentication with Retrofit. However, it provides all necessary fundamentals for a sustainable android client. That’s why we’ll use it as a stable foundation and extend it during future blog posts with further authentication functionality.

The following class defines the basis of our android client: ServiceGenerator.

Retrofit 2


public class ServiceGenerator {

public static final String API_BASE_URL = "http://your.api-base.url";

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

private static Retrofit.Builder builder =
                         new Retrofit.Builder()
                         .baseUrl(API_BASE_URL)
                         .addConverterFactory(GsonConverterFactory.create());

public static <S> S createService(Class<S> serviceClass) {
                    Retrofit retrofit = builder.client(httpClient.build()).build();
                    return retrofit.create(serviceClass);
            }
}

 

JSON Mapping

Retrofit 1.9 ships with Google’s GSON by default. All you need to do is define the class of your response object and the response will be mapped automatically.

When using Retrofit 2, you need to add a converter explicitly to the Retrofit object. Above, we’ve added the following line in our build.gradle file to import the GSON converter for Retrofit 2.

compile 'com.squareup.retrofit2:converter-gson:2.0.0'  

Now you need to add the converter to your Retrofit object. Call.addConverterFactory(GsonConverterFactory.create()) on Retrofit’s builder to integrate GSON as the default JSON converter.

 

Retrofit in Use

Ok, let’s face an example and define a REST client to request data from GitHub. First, we have to create an interface and define required methods.

 

GitHub Client

The following code defines the GitHubClient and a method to request the list of contributors for a repository. It also illustrates the usage of Retrofit’s parameter replacement functionality ({owner} and {repo} in the defined path will be replaced with the given variables when calling the object method).

Retrofit 2


public interface GitHubClient {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
         @Path("owner") String owner,
         @Path("repo") String repo
          );
}

There is a defined class Contributor. This class comprises required class properties to map the response data.


static class Contributor {
      String login;
      int contributions;
}

 

With regard to previous mentioned JSON mapping: the defined GitHubClient defines a method named contributorswith return type List<Contributor>. Retrofit makes sure the server response gets mapped correctly (in case the response matches the given class).

 

API Example Request

The snippet below illustrates the usage of ServiceGenerator to instantiate your client, concretely the GitHub client, and the method call to get contributors using the created client. This snippet is a modified version of the provided Retrofit github-client example.

You need to manually define the base url within the ServiceGenerator to "https://api.github.com/" when executing the GitHub example. Another option is to create an extra createService() method accepting two parameters: the client class and base url.

Retrofit 2


public static void main(String... args) {
// Create a very simple REST adapter which points the GitHub API endpoint.
GitHubClient client = ServiceGenerator.createService(GitHubClient.class);

// Fetch and print a list of the contributors to this library.
Call<List<Contributor>> call =
                     client.contributors("fs_opensource", "android-boilerplate");

          try {
                  List<Contributor> contributors = call.execute().body();
              } catch (IOException e) {
                 // handle errors
             }

          for (Contributor contributor : contributors) {
                 System.out.println(
                 contributor.login + " (" + contributor.contributions + ")");
              }
 }

What Comes Next

The next posts explains how to implement basic authentication with Retrofit. We’ll show code examples to authenticate against webservices or APIs with username/email and password. Further, future posts will cover API authentication with tokens (including OAuth).

We hope you enjoyed this overview and how to make your first request with Retrofit 🙂

Leave a Reply

Your email address will not be published.