Routing requests
Now, let’s examine the routing
block more closely:
routing {
get("/") {
call.respondText("Hello World!")
}
}
This block defines all the URLs that our server will handle. Currently, it only manages the root URL. When this URL is requested, the server returns a text response, “OK”, to the user.
Next, we explore how to return a JSON response:
get("/status") {
call.respond(mapOf("status" to "OK"))
}
Instead of the respondText()
method, we use respond()
, which accepts an object rather than a string. In this example, we pass a map of strings. However, running this code as is will cause an exception, as objects aren’t automatically serialized into JSON. We can overcome this by using the kotlinx-serialization
and ktor-server-content-negotiation
libraries. We begin by adding them to our dependencies:
dependencies {
...
implementation("io...