DEV Community

loading...
Cover image for Writing your first HTTP API using Ktor!

Writing your first HTTP API using Ktor!

kumbharumesh profile image KMeshU ・2 min read

Introduction

Ktor is a Kotlin framework that can be used to create a variety of server (and client-side) applications.

Without further delay, let's start writing the application.

Like Spingboot initializer which creates a Spring boot project with all the dependencies you need to begin quickly, there is a Ktor Project Generator available.

Visit Ktor Project Generator. Choose Gradle Project, Jetty server, and Ktor 1.5.0. Then updated Group, Name, and version as per your requirements. For now, let's not choose anything on the right-hand side from the Server and Client section. Click Build. It will create an archive that contains the base structure of the project where you can start writing your code in the "Application.kt" file.

Extract the archive. Open the project in IntelliJ Idea or any other IDE you are using for Kotlin development. Now you can directly jump to writing the code in the "Application.kt" file.

Update the "Application.kt" as below

import io.ktor.application.*
import io.ktor.response.*
import io.ktor.routing.*

fun main(args: Array<String>): Unit = io.ktor.server.jetty.EngineMain.main(args)

@Suppress("unused")
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
    routing {
        get("/") {
            call.respondText("Hello, world!")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Your first API is ready to execute now. You can run the application using ./gradlew commands or run directly from IntelliJ. (Green triangle icon is shown on the left-hand side of the main function).
Hit HTTP://localhost:8080 from the browser. You should see the output as shown in the image below.

Alt Text

Deep Dive

Engine

Inside the main function, we are specifying the server engine.

fun main(args: Array<String>): Unit = io.ktor.server.jetty.EngineMain.main(args)
Enter fullscreen mode Exit fullscreen mode

To run a Ktor server application, you need to create and configure a server first. EngineMain represents an engine for running a server. Ktor supports the following engines:

  • Netty
  • Jetty
  • Tomcat
  • CIO (Coroutine-based I/O) Ktor also provides a special engine type TestEngine for testing application logic.

You can define different server properties like various engine-specific options, host and port values, and so on in the "application.conf" file under the "resources" folder.

Routing

Ktor Application consists of one or more modules. The module is nothing but a user-defined function that is receiving Application class that is in charge of configuring the server pipeline, install features, registering routes, handling requests, etc.

In the above example module is an extension method of the class Application.

fun Application.module(testing: Boolean = false)

Alt Text

Routing is the one that allows incoming requests to be handled. When a request such as "/" in our case is made, the routing mechanism in Ktor allows us to define how we want this request to be served.
Any route takes three parameters:

  • URL pattern
  • Verb,(GET, POST, PUT, DELETE, HEAD, OPTION, or PATCH)
  • Handler - access to handling the request

You can define multiple routes as shown below.

routing {
    get("/") {

    }
    post("/user") {

    }
    get("/user/{id}") {

    }
}
Enter fullscreen mode Exit fullscreen mode

Cover Photo by Marc Reichelt

Discussion (0)

pic
Editor guide