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

Android Retrofit Tutorial with Example – 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.

18 Comments

  1. clayvander June 19, 2016
  2. Tracee March 28, 2017
  3. school education April 21, 2017
  4. Irshad Ahmed July 28, 2017
  5. Vijender R August 3, 2017
  6. Atul kumar September 26, 2017
    • Rajeev Kumar September 26, 2017
      • Atul kumar September 26, 2017
      • Rajeev Kumar September 27, 2017
      • Atul kumar September 27, 2017
      • Rajeev Kumar September 28, 2017
      • Atul kumar September 29, 2017
  7. Abhishek Dhyani October 9, 2017
  8. Vindhya Vindhu January 10, 2018
  9. Ahmed Suhail February 1, 2018

Leave a Reply