Retrofit — Getting Started and Create an Android Client

This is the first post in a series of Retrofit articles. The series dives through several use cases and examines Retrofits range of functions and extensibility.


Retrofit Series Overview

  1. Getting Started and Create an Android Client
  2. Basic Authentication on Android
  3. Token Authentication on Android
  4. OAuth on Android
  5. Multiple Query Parameters of Same Name
  6. Synchronous and Asynchronous Requests
  7. Send Objects in Request Body
  8. Define a Custom Response Converter
  9. Add Custom Request Header
  10. Optional Query Parameters
  11. How to Integrate XML Converter
  12. Using the Log Level to Debug Requests
  13. How to Upload Files to Server
  14. Series Round-Up
  15. Retrofit 2 — Upgrade Guide from 1.9
  16. Retrofit 2 — How to Upload Files to Server
  17. Retrofit 2 — Log Requests and Responses
  18. Retrofit 2 — Hawk Authentication on Android
  19. Retrofit 2 — Simple Error Handling
  20. How to use OkHttp 3 with Retrofit 1
  21. Retrofit 2 — Book Update & Release Celebration
  22. Send Data Form-Urlencoded
  23. Send Data Form-Urlencoded Using FieldMap
  24. Retrofit 2 — Manage Request Headers in OkHttp Interceptor
  25. Retrofit 2 — How to Add Query Parameters to Every Request
  26. Retrofit 2 — Add Multiple Query Parameter With QueryMap
  27. Retrofit 2 — How to Use Dynamic Urls for Requests
  28. Retrofit 2 — Url Handling, Resolution and Parsing
  29. Retrofit 2 — Constant, Default and Logic Values for POST and PUT Requests
  30. Retrofit 2 — How to Download Files from Server
  31. Retrofit 2 — Cancel Requests
  32. Retrofit 2 — Reuse and Analyze Requests
  33. Retrofit 2 — How to Change API Base Url at Runtime
  34. Optional Path Parameters
  35. How to Refresh an Access Token
  36. Retrofit 2 — How to Send Plain Text Request Body
  37. Retrofit 2 — Pagination Using Query Parameter
  38. Retrofit 2 — Pagination Using Link Header and Dynamic Urls (Like GitHub)
  39. Retrofit 2 — Pagination Using Range Header Fields (Like Heroku)
  40. Retrofit 2 — Introduction to (Multiple) Converters
  41. Retrofit 2 — Adding & Customizing the Gson Converter
  42. Retrofit 2 — Implementing Custom Converters
  43. Retrofit 2 — Enable Logging for Development Builds Only
  44. Retrofit 2 — How to Upload Multiple Files to Server
  45. Retrofit 2 — Passing Multiple Parts Along a File with @PartMap

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 1.9

pom.xml

<dependency>  
    <groupId>com.squareup.retrofit</groupId>
    <artifactId>retrofit</artifactId>
    <version>1.9.0</version>
</dependency>  
<dependency>  
    <groupId>com.squareup.okhttp</groupId>
    <artifactId>okhttp</artifactId>
    <version>2.7.2</version>
</dependency>  

build.gradle

dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.okhttp:okhttp:2.7.2'
}

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.

Service Generator

The ServiceGenerator is our API/HTTP client heart. In its current state, it only defines one method to create a basic REST adapter for a given class/interface. Here is the code:

Retrofit 1.9

public class ServiceGenerator {

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

    private static RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(API_BASE_URL)
                .setClient(new OkClient(new OkHttpClient()));

    public static <S> S createService(Class<S> serviceClass) {
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass);
    }
}

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);
    }
}

The ServiceGenerator class uses Retrofit’s RestAdapter-Builder to create a new REST client with a given API base url. For example, GitHub’s API base url is https://api.github.com/. The serviceClass defines the annotated class or interface for API requests. The following section shows the concrete usage of Retrofit and how to define an exemplary client.

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 1.9

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

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 contributors with 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 1.9

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.
    List<Contributor> contributors =
        client.contributors("fs_opensource", "android-boilerplate");

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

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 :)


Additional Resources


Explore the Library

Find interesting guides and solutions for your problems.

Node.js

Miscellaneous