KtorApp: A basic REST API

Xavi Ribera
3 min readOct 28, 2018

--

In this second part, we will add to our KtorApp a basic Rest Api for messages. The API only has one route with the get, post and delete operations.

In this chapter:

  • We will use Gson, from Google, to parse our JSON classes.
  • Basic log system using Logback.
  • Test our API.

Note: I’ve renamed all the HelloService, HelloRepository, … to a most generic name as MessageService, MessageRepository,…

Ok! Let’s go!

We will change our plain text message “Hello from Kton and Koin” by a class that we will use to return any type of message.

In a new package named “model” we have created the class.

Message Data Class

Now, our MessageRepository looks like this.

getMessage creates a Message with the title and the message

Our MessageService.

Before start the API, we can do a basic configuration for Logback. We have to create a file named logback.xml into resources with the text:

<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>

<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

Now, we have to add to our gradle the Kton/Gson dependences:

The GSON feature allows you to handle JSON content in your application.

and this is our new KtorApp file:

Basic GET / POS/ DELETE api rest

Into Application.main() we need to configure the gson library.

install(ContentNegotiation) {
gson {
setPrettyPrinting()
}
}

Using routing and route commands, we put under the route(“/message”) the methods GET,POST and DELETE for “message” path.

In these methods we use de log variable for logging and it uses the logback.xml configuration.

Special attention to POST method, using Postman to send data in Json format,

{
“message”: “Hello”,
“from”: “Postman”
}

we can transform this information into a Message class:

The method expects a Message class

That’s all! Execute the project and try our new api :).

Testing time!!!

This is our project estructure

Testing

We use hello.json to test our code using always the same data. This file looks like:

{"message":"Hello","from":"Ktor and Koin Test"}

Into KtorAppBaseTest we initialize Koin and a method that we will use to get Json files from resources.

And our tests:

Testing GET
Testing POST
Testing DELETE

As we can see both, Koin and Ktor, makes easy testing our application. From now, we will use TDD methodology to develop next features.

Our the code is in my GitHub repository.

https://github.com/XavRS/KtorApp

Thanks for reading!

--

--