Build Simple REST API Using Vert.x in Kotlin

What is Vert.x?

Have you now about what is Vert.x? Vert.x is an open source, reactive and polyglot software development toolkit from the developers of Eclipse. We call it polyglot because it support multiple languages like Java, Kotlin, Ruby, Groovy, Python and Javascript. Vert.x operates on the Java Virtual Machine (JVM).

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.

- src
| - 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store