Quantcast
Channel: Operating System – TechPrevue
Viewing all articles
Browse latest Browse all 50

Retrofit – A Smart Way to Create REST Client

$
0
0

REST Client is a simple application and also referred to as a useful tool that help explore RESTful web services – that help provide content to mobile devices such as Smartphones and tablets. Creating a REST Client often demands lot of rework, which you can curtail using Retrofit library. This post will let you know about the Retrofit library, and cover topics including: getting weather data of some city using a free API; Representing API calls by setting up an interface; and lastly will be representing how the data is returned from the API.

retrofit iphone app

An Overview of Retrofit

searching for

Retrofit is a library that enable users to describe API in a Java interface, and then convert the API automatically into a REST client.

It’s obvious, in order to use the Retrofit library we will have to download it first, and then will have to install it. However, to achieve this, we have to include Retrofit jar file in the build path. But the jar file will use other libraries if available, and so to obtain maximum benefits of Retrofit, make sure to include all those libraries by adding the following lines to your build.gradle file:

compile 'com.squareup.retrofit:retrofit:1.6.1'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'
compile 'com.squareup.okio:okio:1.0.1'

When you’ve downloaded those libraries and set them up, click on the “Sync Project with Gradle Files” option given in Android Studio, and we can initiate our work.

Implementing a REST Client Application Using Retrofit

retrofit window

In order to get weather related data of a city, let’s say, Boston using an API, we’ll need to use the following:

http://api.openweathermap.org/data/2.5/weather?q= Boston

This will help return weather-related data for Boston. Next, we will have to define a Java interface to describe this API. In order to do so, we’ll create a new java class (Api.java) that contains the following content:

public interface Api {
  @GET("/weather")
  void getWeather(@Query("q") String cityName, 
          Callback callback);
}

Creating the class as mentioned above will help convert the API URL into a format that the Retrofit library can understand. Now look at above code snippet, you can see a GET function is called to the weather endpoint, and is assigned a query string (E.g. q=Boston). Lastly, we’re expecting to receive callback of type WeatherResponse as outcome.

Once we’ve got our interface we need to setup our data model, and then we will begin creating the actual REST Client. For this, we will first have to create a new singleton class (RestClient.java):

public class RestClient {
  private static API REST_CLIENT;
  private static String ROOT = 
          "http://api.openweathermap.org/data/2.5";
  static {
    setupRestClient();
  }
  private RestClient() {}
  public static API get() {
    return REST_CLIENT;
  }
  private static void setupRestClient() {
    RestAdapter.Builder builder = new RestAdapter.Builder()
     .setEndpoint(ROOT)
     .setClient(new OkClient(new OkHttpClient()))
     .builder.setLogLevel(RestAdapter.LogLevel.FULL);
     RestAdapter restAdapter = builder.build();
     REST_CLIENT = restAdapter.create(API.class);
  }
}

The main part of creating the REST Client lies within the setupRestClient() method. In this method we will have to setup Retrofit, so that we can use the Api interface we have created recently, in order to define our endpoints. Now, let’s define our main activity class:

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   RestClient.get().getWeather("Boston", new Callback() {
     @Override
     public void success(WeatherResponse weatherResponse, Response response) {
       // success!
       Log.i("App", weatherResponse.getBase());
       Log.i("App", weatherResponse.getWeather().getMain());
       Log.i("App", weatherResponse.getWeather().getDescription());
       // you get the point...
     }
     @Override
     public void failure(RetrofitError error) {
       // something went wrong
     }
   });
  }
}

There are a few things we need to keep in our mind, first off we need to obtain an instance of our RestClient from our new singleton class. Doing so, will help us get direct access to methods that are defined in “Api.java” interface class. Lastly, the actual API calls will be delivered on the main thread, wherein we can use API values safely when we need to update UI widgets.

Summary
Thanks to Retrofit, you can easily convert your API into a REST Client. This post will provide you a brief understanding of Retrofit library and how you can create a REST Client using Retrofit. We have included an example that will help you understand how to pull Retrofit in your project – that helps to get weather related data for any city.

Author Bio:
mobiersRick Brown is a highly skilled technical writer for Mobiers.com – one of the leading iPhone App Development Companies. To those who are looking forward to Hire iPhone App

You can read more interesting and useful articles on Tech Prevue.


Viewing all articles
Browse latest Browse all 50

Trending Articles