Build Simple REST API Using Vert.x in Kotlin
What is Vert.x?
First thing first
We will create a gradle project to build our simple REST API. Now lets start create our gradle project first.
Change our build.gradle file to add Vert.x dependencies
Now we already had our gradle project then add these lines into build.gradle file.
There is also we update the Jar task since we write in Kotlin so we must add our compiled Kotlin class in our Jar.
Our source files structure
Then we add files structure like this in our source folder.
| - main
| | - java
| | - kotlin
| | | - verticle
| | | | - HttpServerVerticle.kt
| | | | - MainVerticle.kt
| | | - App.kt
App.kt is main function that will run the service.
HttpServerVerticle.kt is the class which our REST API code will be written here.
MainVerticle.kt is main Vert.x instance that will run HttpServerVerticle class.
Create the HTTP Service
Lets edit our HttpServerVerticle, add these lines of code.
First thing first, we define our routes which we will use for our endpoint in line 23. It is some common endpoint that usually use for CRUD stuff.
Then in line 30, we define our Vert.x web service instance.
The rest of the code is our implementation for the API.
Class that will deploy our verticle
The class that responsible to start our Vert.x web service is MainVerticle.kt, we will have this now.
And then App.kt will launch our MainVerticle.
Compile everything that we have and run the REST API service
Once you have finished to write those code, then build it, run the gradle task of cleanAndJar.
If you already had your jar file, just simply run:
$ java -jar build/libs/SimpleRestApi-1.0.0.jar
Now is the time to test our REST API service. I use Postman to test the result of what we have built.
Now we already knew the basic to build REST API using Vert.x in Kotlin. After this we can play around build more complex REST API.
The complete source is on https://github.com/merizrizal/vertx-simple-rest-api