Getting Started with Retrofit 2

In this Retrofit 2 tutorial, we will learn the basics of Retrofit and then we will create an Android client for HTTP requests against a REST API.

1. What is Retrofit?

Retrofit developed by square and in documentation, it is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.

Retrofit android is very simple to use. It essentially lets us treat API calls as simple Java method calls, so we only define which URLs to hit and the types of the request/response parameters as Java classes.

The entire network call + JSON/XML parsing is completely handled by Retrofit (e.g. Gson for JSON parsing). It allows to make a synchronous or asynchronous HTTP request to the remote webserver.

2. Retrofit Installation

To include Retrofit 2 in our project, we shall include following dependencies in build file. In this tutorial, we will be sending and receiving data in JSON format, so we have added converter-gson dependency as well.

<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>retrofit</artifactId>
	<version>2.6.1</version>
</dependency>
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>converter-gson</artifactId>
	<version>2.6.1</version>
</dependency>
dependencies {  
	compile 'com.squareup.retrofit2:retrofit:2.6.1'
	compile 'com.squareup.retrofit2:converter-gson:2.6.1'
}

In Android application, enable Internet permission as well because Retrofit performs HTTP requests against an API running on a server somewhere in the Internet.

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

3. REST API Modeling

3.1. REST API

The next step to use Retrofit is to model the REST API, which we want to consume in application. We are taking example of one such API available to use for free.

HTTP GET https://reqres.in/api/users/2

Response:

{
    "data": {
        "id": 2,
        "email": "janet.weaver@reqres.in",
        "first_name": "Janet",
        "last_name": "Weaver",
        "avatar": "https://s3.amazonaws.com/uifaces
        		/faces/twitter/josephstein/128.jpg"
    }
}

3.2. Service Model

Let’s assume we are only interested in consuming id, name and email fields and we do not want to consume avatar field. The converter, Gson, does not complain in case of there is a mismatch in number of fields. If only populated those fields which names match the response fields.

public class UserApiResponse 
{
	private User data;

	//Setters and getters

	public String toString() {
		return "UserApiResponse [data=" + data + "]";
	}
}
public class User 
{
	private long id;
	private String first_name;
	private String last_name;
	private String email;

	//Setters and getters

	@Override
	public String toString() {
		return "User [id=" + id + ", "
			+ "first_name=" + first_name + ", "
			+ "last_name=" + last_name + ", "
			+ "email=" + email + "]";
	}
}

3.3. Service Interface

Now, we can use the Retrofit annotations to create the service interface with required mapping information and request/response classes.

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface UserService {

    @GET("/api/users/{id}")
    public Call<UserApiResponse> getUser(@Path("id") long id);

}
  • We can use the appropriate Retrofit annotations for each HTTP method: @GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.
  • In the method annotation, we should specify the relative endpoint URL of REST resource. In this case, it is – "/api/users/{id}".
  • In method declaration, we must return the data that is expected from the server wrapped it into a typed Retrofit Call< > class.
  • In method parameter, we can pass path and query parameters, and request body as well in PUT/POST requests.

4. Retrofit 2 in Action

Now it is time to use create Retrofit REST client and make actual API call.

In this example, we are using fluent API with Retrofit.Builder and OkHttpClient to create Retrofit instance.

We provide the base URL for API and converter type.

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserServiceClient 
{
	public static void main(String[] args) 
	{
		OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
		
		Retrofit retrofit = new Retrofit.Builder()
		  .baseUrl("https://reqres.in/")
		  .addConverterFactory(GsonConverterFactory.create())
		  .client(httpClient.build())
		  .build();
		
		UserService service = retrofit.create(UserService.class);
		
		// Calling '/api/users/2'
		Call<UserApiResponse> callSync = service.getUser(2);
		 
		try {
		    Response<UserApiResponse> response = callSync.execute();
		    UserApiResponse apiResponse = response.body();
		    System.out.println(apiResponse);
		} catch (Exception ex) { 
			ex.printStackTrace();
		}
	}
}

Run above program and observe the output printed in console.

UserApiResponse [data=User [
	id=2, 
	first_name=Janet, 
	last_name=Weaver, 
	email=janet.weaver@reqres.in]]

In above example, we have made synchronous request. We will look at async request in coming tutorials.

5. Conclusion

In this tutorial, we learned about Retrofit 2 and built a hello world application for REST client consuming JSON payload. We also gone through the basics of Retrofit library.

Drop me your questions related to above android retrofit get json example in comments.

Happy Learning !!

References: Retrofit Homepage

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Getting Started with Retrofit 2”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.