KtorApp: A basic REST API
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.
Now, our MessageRepository looks like this.
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:
and this is our new KtorApp file:
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:
That’s all! Execute the project and try our new api :).
Testing time!!!
This is our project estructure
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:
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!