Retrofit2 - Simple basic example

Here, I am going to explain the use of retrofit library in android. The tutorial has two api calls, one to get the model class and another to get the JSON as string. Another point is, according to the response we need, we have to pass the appropriate "ConverterFactory" to retrofit object.

The step by step tutorial

1. First add the dependencies in gradle,

 compile 'com.squareup.retrofit2:retrofit:2.1.0'
 compile ''
 compile 'com.squareup.retrofit2:converter-gson:2.1.0'
 // for scalar converter factory
 compile 'com.squareup.retrofit2:converter-scalars:2.1.0'

2. Then create a ApiInterface class and add the api calls we need. The return type of the methods are "Call". One point to note in Call is execute() call is a synchronize call and enqueue() is an asynchronous call. In addition to that, BASE_URL should end with "/", else we will get an IllegalArgumentException

public interface APIInterface {

    //String BASE_URL = "";
    String BASE_URL = "";

    Call> getHeroes();

   Call getSnapToRoad();

3. Now in MainActivity onCreate(), means in UI thread we can call the retrofit API call.

private void getApiCall() {
        Retrofit retrofit = new Retrofit.Builder()

        APIInterface api = retrofit.create(APIInterface.class);
        //Call> call = api.getApiCall();
        Call call = api.getSnapToRoad();
        call.enqueue(new Callback() {
            public void onResponse(Call call, Response response) {
                Log.e(TAG, "response.isSuccessful: "+response.isSuccessful());
                Log.e(TAG, "response.code: "+response.code());
                if (response.isSuccessful()) {
                    Log.e(TAG, "response.body: " + response.body());

            public void onFailure(Call call, Throwable t) {


4. Last point is add the INTERNET permission in manifest.

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

The full source code is, here

Happy Coding
Team Androidians


Popular posts from this blog

AlarmManager and Notification in Android

Open Gallery and get the selected image in appplication

Dismiss or Cancel dialog by swipe gesture