Introduction to Retrofit: Rest client for Android and JAVA

Retrofit is a REST client for Android and Java. It is easy to request web services of REST client. This library makes an easy way to consume webservice API’s in a real quick. It is mainly used to handle many aspects, such as making connections, caching, retrying failed requests and more. It is also considered as a tested library to handle API’s with ease.

The steps to handle API’s using Retrofit 2 are as follows:

Step 1:

Adding the following dependencies in build.gradle of the Android studio Project.

{  
dependencies
// Retrofit & OkHttp
compile ‘com.squareup.retrofit2:retrofit:2.1.0’
 
//JSON parsing
compile ‘com.squareup.retrofit2:converter-gson:2.6.1’
compile ‘com.squareup.retrofit2:converter-gson:2.1.0’
}

Step 2:

Include the Internet permission in the application manifest: AndroidManifest.xml.

<uses-permissionandroid:name="android.permission.INTERNET"/>

Step 3:

Create data models from the JSON response ,so that Retrofit can parse the JSON response and deserialize it to Java objects.Use some one tools to generate Models automatically.

The annotations @Serializable, @Expose are needed in the models.

  @SerializedName("user_Id")
  @Expose
  private Integer userId;

The @Serializable annotation is needed for Gson to map the JSON keys to Java object fields.

The @Expose annotation indicates that the class member should be exposed for JSON serialization or deserialization.

Step 4:

Import data models to Android studio Project.

Step 5:

Creating an instance using the Retrofit Builder class and configure it with a base URL,so we will pass it a URL when calling RetrofitClient.getClient(String baseUrl).

Step 6:

Creating an API interface . This interface can contains methods such as GET,POST,PUT and DELETE.At the top of the method call use annotations According to the HTTP requests.Such annotations are @POST,@GET,etc.

Step 7:

In the OnCreate method in MainActivity, we initialize an instance of the API service interface.Initialize the required fields to call the HTTP requests. Once the API call is made the API service interface method will execute the HTTP request to the API.

Retrofit supports synchronous and asynchronous request execution.

Synchronous request

Synchronous methods provide the ability to use the return value directly, because the operation blocks everything else during your network request.

Code snippet:

  TaskService taskService = ServiceGenerator.createService(TaskService.class);  
  Call<List<Task>> call = taskService.getTasks();  
  List<Task>> tasks = call.execute().body();

Asynchronous request

Asynchronous requests forces you to implement a Callback with its two callback methods: success and failure. When calling the asynchronous getTasks() method from a service class, you have to implement a new Callback and define what should be done once the request finishes.

Code snippet:

TaskService taskService = ServiceGenerator.createService(TaskService.class);  
Call<List<Task>> call = taskService.getTasks();  
call.enqueue(new Callback<List<Task>>() {  
   @Override
   public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
       if (response.isSuccessful()) {
           // tasks available
       } else {
           // error response, no access to resource?
       }
   }
   @Override
   public void onFailure(Call<List<Task>> call, Throwable t) {
       // something went completely south (like no internet connection)
       Log.d("Error", t.getMessage());
   }
}

If we are working with light weight Operations and webservices, it is highly recommended to use Retrofit frameworks since its having minimum threading assistance. It essentially lets you treat API calls as simple as Java method calls, so you only define which URLs to hit and the types of the request/response parameters as Java classes.