REST API with Ktor on Android

Nicola Piriottu
OverApp
Published in
4 min readNov 10, 2021

--

Working as a Android Developer at OverApp, I had the opportunity to study and implement applications using Ktor a framework for creating asyncronous call to Rest API.

In this article, with the help of Giampietro Fronteddu, I will show you how to call all the main HTTP verbs of a rest api, in an application using the MVVM design pattern.

Project structure

The project i will create for this example is following the MVVM design pattern.

Using this pattern will allow us to create a flexible app, so that replacing Ktor with another library, for example Retrofit, will not require much effort as all the data access code is concentrated in a single point of the app.

For this example we will se JSONPlaceholder, a website that exposes a simple REST API with dummy data.

https://jsonplaceholder.typicode.com/

Ktor Requirements

In order to function properly Ktor needs an HTTP engine and Serialization/Deserialization Library. For this project we will use:

  1. The engine CIO (Coroutine-based I/O).
    - implementation “io.ktor:ktor-client-cio:1.6.3”
  2. Te Ktor default Serialization/Deserialization (To parse requests and responses)
    - implementation ‘io.ktor:ktor-client-gson:1.6.3’
  3. (Optional) Some logging libraries to help with debugging.
    - implementation “io.ktor:ktor-client-logging:1.6.1”
    - implementation “ch.qos.logback:logback-classic:1.2.3”

Client implementation

In this example, I’ll show you how to configure the client and make calls.

  • In this code snippet we configure the Ktor client:
    private val client = HttpClient(CIO)
    this lines instantiate the Ktor client using the CIO engine.
  • here we are configuring some default values(DefaultRequest) for our requests, for example we add a Bearer token to the Authorization Header .
  • then we configure the serializer for the client
  • finally we enable request/response to be shown in the Android Studio Terminal.

Request example

Response example

How to execute Ktor request

Response validation
Before we begin, we have to point out that calls need the try/catch construct to work.
It allows us to catch exceptions when the status code is other than 2xx.
I created a class, called NetworkResponseCode, which can return the error code based on the type of exception.

The response is passed through a sealed class called NetworkResponse.

Network Requests

Let’s start with the response model named PostResponse.

Repository

Each request is built with these points:
1) API_WORKER.getClient() which exposes the .get, .post, .put, .delete methods passing the URL as a parameter.
2) Inside this block it’s possible to add optional parameters.
An example is parameter, that allows you to create query strings, for example:
https://jsonplaceholder.typicode.com/posts?id=5
3) the response, in the event of a response with a 2xx result
4) the error code based on the type of exception

  • GET request example

In this first example we created a function that returns a post with id = 5.
A response variable is created, of type HttpResponse, which allows obtaining the response of the call.

  • POST request example

Similarly to the GET, has an object that is passed to the optional body parameter.

In this example, the function receives input parameters.
Through a hashMap an object is constructed to put in the body.

  • DELETE request example
  • PUT request example

Example of use within the ViewModel

Now I show you how to implement the GET request to get a list of posts. For other requests you can refer to this project.

1) getPosts() creates and runs a coroutine by calling callPosts().
2) callPosts() is a suspend, while Dispatchers.IO indicates that this coroutine isn’t executed on the Main thread.
NetworkResponse.Success : shows the list of posts.
NetworkResponse.Error : shows the error code.

Final Thoughts

To better understand Ktor and this article, knowledge of these topics is recommended:

ViewModel, LiveData, Coroutines, sealed class, data class, object.

Thank you for your attention, I hope it was a useful guide.

Created by Nicola Piriottu and Giampietro Fronteddu, Android Mobile Developers at OverApp

--

--