Manage REST API in Kotlin with Okhttp3, Retrofit2, Gson, and Rxjava2

Android has multiple ways to manage Manage REST API. Using some awesome libraries are making it more efficient and awesome. Read the full article and full app source code available on Github.

The topics we will learn are:

  1. Okhttp3
  2. Retrofit2
  3. RxJava
  4. RxAndroid
  5. Gson

Add Dependent Libraries and Permission

Now, to use Okhttp3, Retrofit2, RxJava, RxAndroid, and Gson you’ll need to add the library to your gradle. Add the followings to your build.gradle(Module:app)

OkHttp to make Network Requests

OkHttp offers a request/response API that makes developers life easier. It supports synchronous and asynchronous calls. Even better, OkHttp is also available for Java projects with Java 7 as a requirement. Besides, OkHttp has a great mechanism to manage common connection problems. And now, it supports also WebSocket.

Retrofit Client Builder

Retrofit is a type-safe HTTP client for Android. With Retrofit, we can compose the HTTP connection easily through a simple expressive interface just like an API document. Besides the elegant syntax it provides, it’s also easy to incorporate with other libraries. The interesting fact is POST and GET request the Retrofit.Builder() is same.

POST request

Create an interface class where @POST(“”) annotation is define request type and inside parameter is your suffix of request URL. @QUERY() annotation is request header for you can use it for Authentication. @BODY annotation is data body. Using GSON data class will be convert in JSON format.

GET request

Create an interface class where @GET(“”) annotation is define request type. And @QUERY(“”) is bind request data with your URL.

Parse JSON to data class using GSON

We used Google GSON library to parse JSON to Kotlin data class. @SerializedName(“”) annotation. This is used when the property name in the Kotlin class does not match the field name in JSON. In real API sometime objects are optional. @Expose(deserialize = false) for make a filed optional.

Subscribe to the Observable

With the lambda expressions in Kotlin it’s super easy and clean way to subscribe and grab the data or handle the error. If we want to follow the onNext(), onError() and onComplete() pattern of Subscriber, than we can use RxKotlin which is an extensions for RxJava. Retrofit.Builder is lazy process manage observable with it. On .subscribe is return the result data class.

Hopes you learn something, either a little Okhttp3, Retrofit2, Gson, and Rxjava2, Oh yes, you could get the code from github.

Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.

Software Engineering who has experts on iOS & Android development (https://goo.gl/UAfmBd)

The (retired) Pub(lication) for Android & Tech, focused on Development