How to implement REST API in Android using Retrofit in Kotlin (Part-1)

Rahul Ray
3 min readJun 28, 2020

While developing an Android application we have to communicate to servers and databases for data. Fetching, creating and manipulating of data from android can be done by using REST APIs. In this article I am going to show you how to implement these APIs in an Android application using Retrofit library.

This series is divided into 3 parts: Part 1 covers the implementation of GET request, Part 2 covers POST request and the Part 3, the final one covers the DELETE request.

To switch to next parts scroll down to bottom of this article.

For this series, I am using https://jsonplaceholder.typicode.com/ for sample REST APIs.

First of all create a project in Android Studio.

Select Empty Activity
Set the name of the application, path and programming language (Java/Kotlin)

After creating the project, add some libraries to app/build.gradle file.

These libraries are required

After that, add this also

Now I will arrange my file structure according to MVVM(Model view viewmodel architecture)

This is the file hierarchy

Now we are set to jump right into code!

First let’s create our Model class, i.e; PostModel

PostModel.kt

Now let’s setup the network classes which will help us to handle APIs in which we will create our Retrofit client.

ApiClient.kt

Next we will make an interface called ApiInterface

ApiInterface.kt

Now lets see the function to fetch all the posts.

We will call this method from our viewmodel class.

Next we are going to make layout for main activity. I have added a recyclerview in it.

activity_main.xml

Now create a layout for a particular item of a post.

home_rv_item_view.xml

In our Main Activity, we will initialize our our Recyclerview Adpater and display the fetched result.

Now lets take a look at our adapter till now.

Now we can see our fetched data in our device.

Hence, we have implemented our first REST API via GET request in Android and displayed it using Retrofit.

Next we will create a post using retrofit via POST request in the next story. Click this link to reach there (PART 2).

Stay tuned for next parts too!!

For complete code checkout this github repository.

--

--