Understanding Android Networking Library — Retrofit 2

Before using any new library or framework or any technology, the three things which are needed to look into are What, Why and How.

What?

As the documentation says, it’s a type-safe HTTP client for Android and Java.

Why?

  1. Easy to connect to web-services by translating the API into Java or Kotlin.
  2. Easy to add Headers and request types.
  3. Easily Customisable, you can customise it and add say any convertors like Gson, JackSon, Moshi, Prtobuf, XML etc. You can also customise it to add different interceptors and cache.
  4. It provides additional functionalities such as custom headers, file uploads, downloads, mocking responses (for testing).

How?

I have created a sample weather application and will be using the same for demonstration.

Checkout the repo for full working example(retrofit_example branch)

  1. Add the required dependencies in apps build.gradle

2. Create the ApiClient/ApiService

http://api.apixu.com/v1/forecast.json?key=ADD_YOUR_KEY&q=Bangalore&days=4

Above api, is used here to get the weather data for four days. Create your own api key and add the same in the query param.

The interface ApiService, creates a method called getWeatherData with query params and GET as an endpoint.

WeatherForecast is the data class generated from json response. Any built-in plugins can be used to generate the same in android studio for both Java and Kotlin.

Few points to be noted here —

  1. This is where you define all the methods for different web services.
  2. Along with the methods, it needs the api endpoints description.Such as request type to be used and request params. Checkout here for more info for describing the api endpoints.
  3. The method returns the pojo class wrapped up inside the Call interface by retrofit. This is just a callback given by the retrofit to perform the request synchronously or asynchronously.

3. Create Retrofit and ApiServiceImplementation

The provideRetrofit() function, is responsible for creating an Retrofit instance.

It uses the Builder pattern and takes the BaseUrl and the Convertor for parsing json to data class and HtppClient.

Note — Retrofit 2 uses Okhttp3 under the hood, so there is no need to add additional dependency for the same.

Now, the provideApiService() returns the implementation. All you need to do is give the apiservice interface to the Retrofit and it will create the interface implementation.

Okay, So far so good…!!!

Now, the last thing need to be done is to make use of the apiservice we created.

And we are done.

References :-