dcsimg
December 3, 2016
Hot Topics:

An Amazingly Easy Way to Consume Android APIs with Retrofit

By Ashesh Shah

Retrofit from Square is a type-safe REST client for Android. This is a library providing a powerful framework that interacts with, as well as authenticates, APIs, by making use of OkHttp to send network requests.

The library makes use of a Web API for downloading XML or JSON data. After the data is downloaded, the parsing takes place into Plain Old Java Object, popularly known as "POJO," defined for every single resource to respond.

What Libraries Are Needed

We do need libraries to make use of Retrofit for Android projects, for checking dependencies. There is also a converter needed for the JSON format: GSON.

compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.google.code.gson:gson:2.3'

How to Construct an Android Client

Let us discuss the necessary fundamentals to create an Android client with a systematic structure. To achieve this, we need to have at least one interface in place for jotting down the RESTclient, API responses, model classes, and query lists.

1. Create POJOs

You have Retrofit accompanying GSON by default. However, there is one thing we need to do in this first step. You need to have model classes defined for the response object, so that it can be mapped.

public class Contributor {
   public String login;        // GitHub username.
   public int contributions;   // Commit count.
}

Often, you can go for different names, by using a @SerializedName annotation, which lets you specify the JSON field name.

public class DeviceResponse extends BaseResponse {

   @SerializedName("device_id")
   public Integer deviceId;

   @SerializedName("all_full")
   public boolean isCompleted;
}

You need to be cautious regarding one thing here. A base response model class needs to be defined if you want to develop an OOP-based standard application that is well defined.

public class BaseResponse {

   @SerializedName("msg")
   public String msg;

   @SerializedName("status")
   public int status;
}

2. Create a RestInterface Class

You can manage the various URL calls by making use of an interface named RestInterface, which needs to be created. Specify the request type such as PUT, GET, POST, and so forth.

public interface RestInterface {

   @GET("/video/list")
   void getPlaces(@Query("key") String key,
      Callback<List<VideosWrapper>> places);

   @GET("/faq/list")
   FaqResponse getFaq(@Query("key") String key,
      @Query("code") String code);

   @POST("/device/save")
   DeviceResponse saveDevice(@Body Device device,
      @Query("key") String key);

   @FormUrlEncoded
   @POST("/user/remind")
   BaseResponse remindPassword(@Field("email") String email,
                               @Query("key") String key);

}

I have just featured a few requests. To learn to specify a range of different requests, visit the official Retrofit Web site page.

3. Create a RESTclient

When creating a RESTclient, you need to have a base class first, called BaseService. Define a few common features, such as API end point, StethoUtil, OkHttpClient, and so on. Within this base service class, you can define the rest of the service classes.

It is best to group all these classes into varied different subclasses, based on the API structure. As an example, within a rest service class, can have all the stuff related to login, register, and the like. Define a UserService class, which will fit the best in this situation.

public final class UserService {

   private static final RestInterface api = BaseService.getApi();

   private UserService() {

   }

   public static BaseResponse remindPassword(String email) {
      BaseResponse response = new BaseResponse();
      try {
         response = api.remindPassword(email,
                    BuildConfig.REST_KEY);
      } catch (RetrofitError error) {
         if (error.getKind() == RetrofitError.Kind.NETWORK
         || error.getKind() == RetrofitError.Kind.UNEXPECTED) {
            response.msg = error.getMessage();
         } else {
            response.msg = error.getMessage();
         }
         Timber.e(error.getMessage());
      } catch (Exception e) {
         response.msg = e.getMessage();
         Timber.e(e.getMessage());
      }
      return response;
   }
}

When Otto Meets Retrofit

Retrofit is quite certainly not the best fit for supporting requests that are asynchronous. This is because such requests do not have a return type. A better option is to define a typed callback method, as a last method parameter.

public void getAllSongList() {

   restService.getAllSongList(new Callback<SongWrapper>() {

      @Override
      public void success(SongWrapper songWrapper, Response response{
         BusProvider.getInstance().post(new
            OnAllSongListFetchedEvent(songWrapper.getSongs()));
      }

      @Override
      public void failure(RetrofitError error) {
         Log.v(TAG, error.getMessage());
      }
   });
}

Better get yourself subscribed to the bus. It is ideal to watch events that demand an API call. As soon as the event gets caught, there is a callback creation, firing a new event after the successful completion of a response.

Final Thoughts

After using Retrofit, you soon realize that you have a much smoother relationship with Android APIs that are based on HTTP.

About the Author

Ashesh Shah is the CEO of Fusion Informatics Ltd. and co-founder of Digital Infoware Pvt. Ltd., which are progressive enterprises in the field of software, mobile app, and Web site design, as well as development services.


Tags: XML, JSON, REST, API, Android, HTTP, POJO, Retrofit, OkHttp, GSON, RESTclient




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel