You always wanted to make your own server as an Android Kotlin developer?
Here are some small things to know to kickstart your first Ktor app.
First of all, what is Ktor.
It is a straightforward and very powerful tool to build asynchronous clients and servers apps with Kotlin and coroutines.
It's fun, like many things with Kotlin. And it's built and backed by JetBrains.
One of the options to start a Ktor project is via start.ktor.io
Define the app name, package name, ktor version, the engine used and what plugins you need.
For a simple backend which stores datas and provides apis you need these plugins :
- Content negotiation and serialization for transforming data transfer object (data class) into json
- Routing for communicating from the outside with your Ktor application
Here is the basic setup for a newly created app
You'll find
- The main entry point (function main)
- The engine used (here Netty), address and port
- Serialization and routing configs
You need to declare all your DTO (data transfer objects) accompanied by their serialized annotation
In the configureRouting method you need to register the routes
We'll see different kind of routes. You'll learn how to respond, get and check url params, get a post body.
Here is a very simple route that returns a list of objects
Here is a get route that get params in url, check param and may returns either errors (bad request / not found) or the actual object
call.parameters["param"] gets the param passed in the call
Post route with a body
call.receive waits the exact json body with all the customer properties i.e id, firstName, lastName and email.
Later, you will want authentication
A simple way is to separate public calls from private calls wrapping routes with authenticate lambda
That way if you don't provide the token bearer in headers, the authenticate routes will automatically return 401, "Unauthorized"
Finally, I advise you to build your apis using Insomnia
It's a great tool to create, test, maintain and document your APIs.