Retrofit 2 Tutorial: Declarative REST Client for Android

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

1. What is Retrofit?

Retrofit was developed by Square and in its documentation, it is a 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 web server.

2. Retrofit Installation

To include Retrofit2 in our project, we shall include the following dependencies in the 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 whose names match the response fields.

public class UserApiResponse {
  private User data;
}
public class User {
  private long id;
  private String first_name;
  private String last_name;
  private String email;
 
  //Setters and getters
}

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 and wrap it into a typed Retrofit Call< &gt 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 the Retrofit REST client and make an 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 the 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 went through the basics of the Retrofit library.

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

Happy Learning !!

Sourcecode Download

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode