Retrofit 2

  • Ivan Žarković

Hello reader,

in this article, I will write about a widely used Java tool for communication with web services. This little interface helped me to understand how web API's work (how I can write and read data from a distant server/database with no trouble). All I needed is to develop few backend scripts in PHP which communicate with MySQL (simple CRUD API) and to link it with my Android application. I have been using it since with almost every Android project I am working on.

Retrofit is the REST library for Java (mostly Android). It is used to retrieve or upload JSON to a web API via REST-based web services. We can easily configure converter which is used for data serialization (JSON, XML, or other protocols...). Retrofit uses the OkHTTP library for managing HTTP requests. As official docs say, Retrofit turns your HTTP API into a Java interface :

public interface SampleService {
  @GET("data")
  Call<List<Data>> listData(@Path("data") String data);
}

Builder

With Retrofit builder, we initialize service URL

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

Converters

We can also add a converter that is used for, let's say, equalize formats from Android client to Server. Practically that means converting data on both sides into the same format. In this example, I am using GSON converter (com.squareup.retrofit2:converter-gson)

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

There are a few more converters which can be used:

  • SimpleXML - com.squareup.retrofit2:converter-simplexml
  • Moshi - com.squareup.retrofit2:converter-moshi
  • Jackson - com.squareup.retrofit2:converter-jackson
  • Protobuff - com.squareup.retrofit2:converter-protobuf

Request methods

Retrofit has five built-in methods. GET, POST, PUT, DELETE and HEAD.

Model serialization

For data to be retrieved we need to create the serializable model class. Easiest way to do that is by using online tools like this JSON schema POJO

 

I've made a sample of how to implement Retrofit library in Android application to get data from REST API. Find out more on GitHub.

You can check API on Rick & Morty.

 

For more detailed explanation refer to Retrofit Documentation

Article Subscription