Building a REST API with Ktor

Bill Wixted
Feb 11 · 6 min read
The Ktor library

repositories {
mavenCentral()
jcenter()
maven { url "https://kotlin.bintray.com/ktor" }
}

dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile "io.ktor:ktor-server-netty:$ktor_version"
compile "io.ktor:ktor-html-builder:$ktor_version"
compile "ch.qos.logback:logback-classic:1.2.3"
testCompile group: 'junit', name: 'junit', version: '4.12'
}
fun main(args: Array<String>) {
val server : NettyApplicationEngine = embeddedServer(Netty, port = 8080) {
...
}
module: Application.() -> Unit
class Application(val environment: ApplicationEnvironment) : ApplicationCallPipeline(), CoroutineScope {
install(StatusPages) {
exception<Throwable> { e ->
call.respondText(e.localizedMessage,ContentType.Text.Plain, HttpStatusCode.InternalServerError)
}
}
routing {

get("/") {
getServerInfo(call)
}

// returns a list of macs for the manufacturer given in 'id'
get("/mac/{id}") {
getMacAddress(call)
}

// returns the manufacturer for the mac given in 'id'
get("/manuf/{id}") {
getManufacturer(call)
}

// returns the manufacturer for the mac given in 'id'
get("/manuf/") {
getAllManufacturers(call)
}

}
suspend fun getServerInfo(call: ApplicationCall) {

call.respondHtml {
head {
title { +"KtorServer Info" }
}
body {
h1 {
+"KtorServer"
}
p {
+"This server provides OUIs (Organizationally Unique Identifiers) that have been assigned to a manufacturer by IEEE."
+"You can lookup OUIs using the manufacturer name and also discover the manufacturer for a given OUI."
+"See the GitHub site for more information: https://github.com/bwixted/ktorserver"
}
}
}
// returns a list of macs for the manufacturer given in 'id'
get("/mac/{id}") {
getMacAddress(call)
}
http://127.0.0.1:8080/mac/freebox
[00:07:CB, 34:27:92, 68:A3:78, 14:0C:76, F4:CA:E5, 00:24:D4, E4:9E:12]
suspend fun getMacAddress(call: ApplicationCall) {
val id = call.parameters["id"]

if (id != null) {
val mac = DeviceManager.findMac(id)
if (mac.isEmpty())
call.respondText("Not Found", ContentType.Text.Plain)
else {
call.respondText(mac.toString(), ContentType.Text.Plain)
}
} else {
call.respond(HttpStatusCode.NotFound, "Invalid request!")
}
}

Bill Wixted

Written by

Android Developer at Platform Science inventing a fleet management platform leveraging cloud, IoT, and mobile. Also developer of Network Explorer app.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade