Android Retrofit Library Tutorial With Example




Android Retrofit library is a type-safe HTTP client for Android and Java built by square. This library is easy to learn and has many features. You can send various requests like GET, POST, PUT, DELETE using retrofit library. You can easily retrieve and upload JSON to a rest based web service using retrofit library. Generally, we use Gson converter for JSON. But, we can add custom converters as well to process XML or other protocols. Retrofit library uses OkHttp library for HTTP requests.

Output

Note: You will get output shown as above after completing 2nd part of this tutorial.

Source Code

1. Getting started

We will use REST API provided by StackOverflow. You can go to stackexchange api docs and check out many options provided by stackOverflow. Using these apis, we can send many requests, for example – Get top voted questions from stackoverflow, Get Recent activities in stackoverflow etc.

In this tutorial, our target is to get all the questions in stackoverflow which is tagged as android. The complete url is

 https://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=android&site=stackoverflow 

1.1 Creating a new project

Follow steps written below to create a new project.
a. Goto File –> New –> New Project. Then, Write application name as RetrofitLibrary and click next.
b. Select Minimum SDK 16 –> click next –> Select Empty Activity –> click next –> click finish.
If you have followed above process correctly, you will get a newly created project successfully.

At this time, you will have folder structures as below.

Android project structure for retrofit library

Tutorialwing – project structure

1.2 Add Gradle for Retrofit library and Gson

Open app/build.gradle and add gradle for retrofit and Gson in it.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
}

1.3 Add internet permission in AndroidManifest.xml

Since we are going to do network operations, we need to add internet permission in AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest package="tutorialwing.com.retrofitlibrary"
		  xmlns:android="http://schemas.android.com/apk/res/android">

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

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".activity.MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

Generally, we need 3 classes to use retrofit library –
a. Retrofit builder class: Build an instance of retrofit that is used to send any HTTP request.
b. Model class: This is representation of JSON in java.
c. APIService interface: This is interface which defines possible operations. for example – send GET, POST, PUT etc. request.

Before we proceed, Let’s create subfolders activity, model and rest in tutorialwing.com.retrofitlibrary package to structure the project. Then, move MainActivity.java class under activity package.

1.4 Create an instance of Retrofit

We need to create a retrofit instance to send request to API. So, create a class named RestClient in rest package and write code as below to create an retrofit instance. While creating instance, we need to define base url of all requests. In this case, base url is https://api.stackexchange.com

rest/RestClient class

package tutorialwing.com.retrofitlibrary.rest;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RestClient {

	public static final String BASE_URL = "https://api.stackexchange.com";
	private static Retrofit retrofit = null;

	public static Retrofit getClient() {
		if (retrofit==null) {
			retrofit = new Retrofit.Builder()
					.baseUrl(BASE_URL)
					.addConverterFactory(GsonConverterFactory.create())
					.build();
		}
		return retrofit;
	}
}

1.5 Create Model class

Before we create model class, we need to know what will be the content of model class. Model class is representation of JSON in java. So, we need to know about contents of JSON. The url of JSON we are using for this tutorial is

 https://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=android&site=stackoverflow 

If you want to see this json in proper format, then, copy the json content, go to Online Json Viewer and paste it there. Finally, json will look as below.

tutorialwing json in proper format

tutorialwing – json in proper format

For the sake of simplicity of this post, we are interested in only title and link of every question. Consider each question as an object. Then, this JSON contains list of many objects(i.e. list of Question). Create model class Question and QuestionList in model package. Finally, our model class will look like below.
model/Question class

package tutorialwing.com.retrofitlibrary.model;

//This class is used to map the json keys to the object
public class Question {

	String title;
	String link;

	public String getTitle() {
		return title;
	}

	public String getLink() {
		return link;
	}
}

model/QuestionList class

package tutorialwing.com.retrofitlibrary.model;

import java.util.List;

public class QuestionList {

	List<Question> items;

	public List<Question> getQuestions() {
		return items;
	}
}

1.6 Create APIService interface

Till now, we have created model class and class to return an instance of retrofit. Now, we need to define the apiService which sends the request to api. Annotations on the interface methods and parameters defines how a sent request will be handled. Every methods must contain the HTTP annotation that provides the request method and relative URL. For example, If you want to post some data, you need to use @POST(end url). If you want to fetch some data, you need to use @GET(end url) etc.

GET Annotation

@GET("end url")
Call<QuestionList> getQuestionList(@Query("tagged") String tags);

POST Annotation

@POST("end url")
Call<Question> postQuestion(@Body Question question);

Note: end url used in the examples is partial url after the base url to which you are sending request.

There are five built-in annotations – GET, POST, PUT, DELETE, and HEAD. Here, we are using only GET annotation. Go to Different Built-In Annotations to know more about other annotations.

Also, Each method can have special annotations like @Query, @Path, @Body etc. Based on the requirements, we use these special annotation. Go to Annotations to know more about these annotations.




In this tutorial, our target is to fetch all the questions with tag android. So, we will use @GET and @Query annotations.

Our APIService class will be like below. Create a class QuestionAPIService in rest package and copy/paste below code.
rest/QuestionAPIService interface

package tutorialwing.com.retrofitlibrary.rest;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
import tutorialwing.com.retrofitlibrary.model.QuestionList;

public interface QuestionAPIService {
	@GET("/2.2/questions?order=desc&sort=creation&site=stackoverflow")	//End Url
	Call<QuestionList> fetchQuestions(@Query("tagged") String tags);
}

Notice that end url in method fetchQuestions is

"/2.2/questions?order=desc&sort=creation&site=stackoverflow"

and base url is

"https://api.stackexchange.com"

. So, Complete url for request will be base-url + end-url =

" https://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=android&site=stackoverflow".

Also, Each method always returns parameterised Call< T > object. In this case, it is Call< QuestionList >.

2. Finally, Make request to fetch Data

Till now, we have successfully created APIServiceInterface, Model class and an Instance of Retrofit. Now, we will use these classes to make request to fetch questions with tag android. Inside MainActivity.java, write the code as below to send the request to fetch all the questions tagged as android.
activity/MainActivity class

package tutorialwing.com.retrofitlibrary.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import tutorialwing.com.retrofitlibrary.R;
import tutorialwing.com.retrofitlibrary.model.QuestionList;
import tutorialwing.com.retrofitlibrary.rest.QuestionAPIService;
import tutorialwing.com.retrofitlibrary.rest.RestClient;

public class MainActivity extends AppCompatActivity {

	private static final String TAG = MainActivity.class.getSimpleName();

	QuestionAPIService apiService;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		apiService = RestClient.getClient().create(QuestionAPIService.class);
		fetchQuetionList();
	}

	private void fetchQuetionList() {
		Call<QuestionList> call = apiService.fetchQuestions("android");
		call.enqueue(new Callback<QuestionList>() {
			@Override
			public void onResponse(Call<QuestionList> call, Response<QuestionList> response) {
				Log.d(TAG, "Total number of questions fetched : " + response.body().getQuestions().size());
			}

			@Override
			public void onFailure(Call<QuestionList> call, Throwable t) {
				Log.e(TAG, "Got error : " + t.getLocalizedMessage());
			}
		});
	}
}



Output

If you run the app at this point, you will see the total number of questions fetched(that are tagged as android) in your Logcat. Below is output snippet.

android retrofit logcat output

android retrofit output in logcat

Go to Show Json Response Using retrofit to know more about android retrofit library or to know how to use android retrofit library with RecyclerView.

Conclusion

Android Retrofit library is a simple, easy to learn and use, yet powerful android library for rest based web services. You can make synchronous as well as asynchronous calls through it. You can easily send request like GET,POST,PUT, DELETE using this library. Go to Advance concepts of Retrofit to know advance concepts about retrofit. Hope this tutorial helped you.

Support Us

If you have any suggestion about this post, please comment below. We are looking for someone who helps use to make our tutorial better. Also, If you want tutorials on any topic, you can mail us at tutorialwing@gmail.com. We will try to cover the topic as soon as possible. Connect with us on Facebook, Google+, Twitter and Youtube for more updates.

  • clayvander

    Excellent post. I certainly love this website.

    Continue the good work!

  • Pingback: Google()

  • Tracee

    Heey very nice blog!

  • school education

    If some one desires expert view concerning running a blog then i advise him/her to visit this weblog, Keep up the good job.

  • Irshad Ahmed

    Cool Vlog man!
    I suggest you even checkout this Volley tutorial:
    https://androidclarified.wordpress.com/2017/07/15/android-volley-example/

  • Vijender R

    Phenomenal tutorial. So simple and brilliantly explained!

    • Rajeev Kumar

      Thank you Vijender .. 🙂

  • Atul kumar

    iam currently facing an problem which
    iam unable to solve , the problem is iam trying to post arraylist of
    object to server in order to store the values in the database , but iam
    unable to do and iam getting error , could you please go through my code
    and point out my mistake , the code and error is in the link below:-

    https://github.com/atul92cs/Sqlite4

    thanks in advance

    • Rajeev Kumar

      Please make sure you have created model classes according to your json response. By looking at your error message, it is clear that Gson expects a JSON object(response starting with “{” ) but you are providing a string ( reponse starting with ” ) .

      For more detail help, i need to see your json response.

      • Atul kumar

        this is the response i’m getting :-

        {“Order Summary”:
        [
        {
        “ProductName”:”Wine”,
        “ProductPrice”:”500″,
        “ProductQuantity”:”2″,
        “ProductCost”:”1000″,
        “SellerId”:”2″

        },
        {
        “ProductName”:”Whiskey”,
        “ProductPrice”:”1000″,
        “ProductQuantity”:”1″,
        “ProductCost”:”1000″,
        “SellerId”:”1″

        }
        ]}

        • Rajeev Kumar

          Assuming your response is :
          {
          “OrderSummary” : [
          {
          “ProductName” : “Wine”,
          “ProductPrice” : 500,
          “ProductQuantity” : 2,
          “ProductCost” : 1000,
          “SellerId” : 2
          },
          {
          “ProductName” : “Whiskey”,
          “ProductPrice” : 1000,
          “ProductQuantity” : 1,
          “ProductCost” : 1000,
          “SellerId” : 1
          }
          ]
          }

          You should make model classes as below

          • Atul kumar

            Found out my problem as the data i’m sending is as the following :-
            {“Order Summary”:
            “[
            {
            “ProductName”:”Wine”,
            “ProductPrice”:”500″,
            “ProductQuantity”:”2″,
            “ProductCost”:”1000″,
            “SellerId”:”2″

            },
            {
            “ProductName”:”Whiskey”,
            “ProductPrice”:”1000″,
            “ProductQuantity”:”1″,
            “ProductCost”:”1000″,
            “SellerId”:”1″

            }
            ]”}
            these extra double quotes which is there in the beginning and the end is creating problem to read the data, could help me out in removing these quotes?

          • Rajeev Kumar

            To Solve this, i need your code sample. 🙂

          • Atul kumar

            this is the code where i have created my json object please go through and tell me the changes which i can make :-
            private void loadCart()
            {

            Cursor cursor = dbHelper.getCarProducts();
            cursor.moveToFirst();
            do {
            CartProduct product = new CartProduct();
            product.setProductName(cursor.getString(cursor.getColumnIndex(“_Name”)));
            product.setProductPrice(cursor.getString(cursor.getColumnIndex(“_Price”)));
            product.setProductQuantity(cursor.getString(cursor.getColumnIndex(“_Quantity”)));
            product.setProductCost(cursor.getString(cursor.getColumnIndex(“_Cost”)));
            product.setSellerId(cursor.getString(cursor.getColumnIndex(“_Sellerid”)));
            productList.add(product);

            }while(cursor.moveToNext());
            Cart = new JSONObject();
            try
            {
            Gson gson = new Gson();
            userCart=gson.toJson(productList);
            Cart.put(“OrderSummary”,userCart);
            }
            catch (Exception ex)
            {

            }

            for(int i=0;i<userCart.length();i++)
            {
            totalCost.append(Cart.toString());
            }

            pDialog.hide();
            }

  • Abhishek Dhyani

    Very nice tutorial