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.


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 

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 ''
    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=""

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

		<activity android:name=".activity.MainActivity">
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>


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 package to structure the project. Then, move 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

rest/RestClient class


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

public class RestClient {

	public static final String BASE_URL = "";
	private static Retrofit retrofit = null;

	public static Retrofit getClient() {
		if (retrofit==null) {
			retrofit = new Retrofit.Builder()
		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 

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


//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


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


import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

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


and base url is


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


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, write the code as below to send the request to fetch all the questions tagged as android.
activity/MainActivity class


import android.os.Bundle;
import android.util.Log;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

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

	QuestionAPIService apiService;

	protected void onCreate(Bundle savedInstanceState) {

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

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

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


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.


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 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:

  • 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:-

    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”:



        • 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”:


            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();
            do {
            CartProduct product = new CartProduct();

            Cart = new JSONObject();
            Gson gson = new Gson();
            catch (Exception ex)


            for(int i=0;i<userCart.length();i++)


  • Abhishek Dhyani

    Very nice tutorial