Ktor Server Core library providing foundational infrastructure for building asynchronous web applications and REST APIs with Kotlin
npx @tessl/cli install tessl/maven-io-ktor--ktor-server-core@3.2.0Comprehensive server-side framework for building asynchronous servers and clients in connected systems using Kotlin coroutines. Ktor Server Core provides the foundational infrastructure for creating web applications and REST APIs with built-in support for routing, request/response handling, content negotiation, and plugin architecture.
io.ktor:ktor-server-corebuild.gradle.ktsdependencies {
implementation("io.ktor:ktor-server-core:$ktor_version")
}// Core application and server functionality
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.routing.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.config.*
// HTTP utilities and content handling
import io.ktor.http.*
import io.ktor.server.plugins.*import io.ktor.server.engine.*
import io.ktor.server.netty.*
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("Hello, Ktor!")
}
}
}.start(wait = true)
}fun main() {
val server = embeddedServer(Netty, port = 8080) {
install(Routing)
routing {
get("/health") {
call.respondText("OK")
}
}
}
server.start(wait = true)
}Ktor Server Core follows a pipeline-based architecture with several key components:
The ApplicationCallPipeline processes incoming requests through phases:
Ktor uses a powerful plugin architecture where functionality is added through installable plugins. Each plugin can intercept and modify the request/response pipeline.
Multiple engine implementations support different deployment scenarios:
Manage application lifecycle, install and configure plugins, and handle application events.
// Application creation and configuration
fun Application.module() {
install(ContentNegotiation) {
json()
}
monitor.subscribe(ApplicationStarted) { application ->
application.log.info("Application started")
}
}
// Plugin installation and access
val plugin = application.plugin(ContentNegotiation)
val pluginOrNull = application.pluginOrNull(SomePlugin)Define URL routes, handle different HTTP methods, and capture path parameters.
routing {
// HTTP method routes
get("/users") { call.respond(users) }
post("/users") { /* create user */ }
// Path parameters
get("/users/{id}") {
val userId = call.parameters["id"]
call.respond(getUserById(userId))
}
// Route groups
route("/api/v1") {
get("/status") { call.respondText("API v1 OK") }
}
}Handle incoming requests, process content, and send responses with proper content types.
// Request processing
get("/upload") {
val content = call.receive<String>()
val contentType = call.request.contentType()
val headers = call.request.headers
call.respondText("Received: $content")
}
// Response generation
post("/api/data") {
val data = processRequest()
call.respond(HttpStatusCode.Created, data)
}Configure and start server engines, manage connectors, and handle deployment scenarios.
// Embedded server with custom configuration
val server = embeddedServer(
factory = Netty,
host = "0.0.0.0",
port = 8080,
configure = {
// Engine-specific configuration
connectionGroupSize = 2
workerGroupSize = 5
callGroupSize = 10
}
) {
// Application configuration
module()
}Load and manage application configuration from various sources including files, environment variables, and command line arguments.
// Configuration loading
val config = applicationEnvironment {
config = HoconApplicationConfig(ConfigFactory.load())
}
// Configuration access
val port = config.config("server").property("port").getString().toInt()
val environment = config.propertyOrNull("environment")?.getString() ?: "development"// Main application class
class Application internal constructor(
environment: ApplicationEnvironment,
developmentMode: Boolean,
rootPath: String,
monitor: Events,
parentCoroutineContext: CoroutineContext,
engineProvider: () -> ApplicationEngine
) : ApplicationCallPipeline, CoroutineScope {
val engine: ApplicationEngine
val rootPath: String
val monitor: Events
suspend fun disposeAndJoin()
}
// Base application call interface
interface ApplicationCall : CoroutineScope {
val attributes: Attributes
val request: ApplicationRequest
val response: ApplicationResponse
val application: Application
val parameters: Parameters
suspend fun <T> receiveNullable(typeInfo: TypeInfo): T?
suspend fun respond(message: Any?, typeInfo: TypeInfo?)
}
// Main pipeline call interface (extends ApplicationCall)
interface PipelineCall : ApplicationCall {
override val request: PipelineRequest
override val response: PipelineResponse
}// Base plugin interface
interface Plugin<
in TPipeline : Pipeline<*, PipelineCall>,
out TConfiguration : Any,
TPlugin : Any
> {
val key: AttributeKey<TPlugin>
fun install(pipeline: TPipeline, configure: TConfiguration.() -> Unit): TPlugin
}
// Base application plugin interface
interface BaseApplicationPlugin<
in TPipeline : Pipeline<*, PipelineCall>,
out TConfiguration : Any,
TPlugin : Any
> : Plugin<TPipeline, TConfiguration, TPlugin>
// Application plugin interface
interface ApplicationPlugin<out TConfiguration : Any> :
BaseApplicationPlugin<Application, TConfiguration, PluginInstance>
// Plugin installation and access
fun <A : Pipeline<*, PipelineCall>, F : Any> A.plugin(plugin: Plugin<*, *, F>): F
fun <A : Pipeline<*, PipelineCall>, F : Any> A.pluginOrNull(plugin: Plugin<*, *, F>): F?// Application engine interface
interface ApplicationEngine {
val environment: ApplicationEnvironment
fun start(wait: Boolean = false): ApplicationEngine
suspend fun startSuspend(wait: Boolean = false): ApplicationEngine
fun stop(gracePeriodMillis: Long = 500, timeoutMillis: Long = 500)
suspend fun resolvedConnectors(): List<EngineConnectorConfig>
}
// Server configuration
data class ServerConfig(
val environment: ApplicationEnvironment,
val rootPath: String = "",
val developmentMode: Boolean = false,
val parentCoroutineContext: CoroutineContext? = null
)Ktor provides structured error handling with specific exception types:
// HTTP exceptions
class NotFoundException(message: String? = "Not Found") : Exception(message)
class MissingRequestParameterException(parameterName: String) : Exception()
class ParameterConversionException(
parameterName: String,
type: String,
cause: Throwable? = null
) : Exception()
// Plugin exceptions
class DuplicatePluginException(key: String) : Exception()
class MissingApplicationPluginException(key: AttributeKey<*>) : Exception()Application lifecycle events for monitoring and hooks:
// Application events
object ApplicationStarting : EventDefinition<Application>()
object ApplicationStarted : EventDefinition<Application>()
object ServerReady : EventDefinition<ApplicationEngine>()
object ApplicationStopping : EventDefinition<Application>()
object ApplicationStopped : EventDefinition<Application>()
// Event subscription
application.monitor.subscribe(ApplicationStarted) { app ->
app.log.info("Application has started successfully")
}// Standard HTTP exceptions from io.ktor.server.plugins
class NotFoundException(message: String? = "Not Found") : Exception(message)
class MissingRequestParameterException(parameterName: String) : Exception()
class ParameterConversionException(
parameterName: String,
type: String,
cause: Throwable? = null
) : Exception()
class CannotTransformContentToTypeException(type: TypeInfo) : Exception()
class UnsupportedMediaTypeException(contentType: ContentType) : Exception()
class PayloadTooLargeException(message: String) : Exception()// Thread-safe utilities from io.ktor.server.util
class CopyOnWriteHashMap<K, V> : MutableMap<K, V>
interface Parameters : StringValues
// Path utilities
fun normalizePathComponents(components: List<String>): List<String>
// URL building utilities
fun URLBuilder.createFromCall(call: ApplicationCall): URLBuilder
fun url(block: URLBuilder.() -> Unit): String// HTTP content and status utilities from io.ktor.server.http
class HttpStatusCodeContent(
val statusCode: HttpStatusCode,
val message: String
)
// Link header utilities
object LinkHeader {
fun parse(value: String): List<LinkHeaderValue>
fun render(links: List<LinkHeaderValue>): String
}
// HTTP/2 Push support
object Push {
fun buildPushPromise(call: ApplicationCall, block: ResponsePushBuilder.() -> Unit)
}// Logging utilities from io.ktor.server.logging
class Logging {
companion object {
fun configure(level: Level, appenders: List<String>)
}
}
// MDC (Mapped Diagnostic Context) provider
interface MDCProvider {
fun withMDCBlock(block: () -> Unit)
fun put(key: String, value: String?)
fun get(key: String): String?
fun clear()
}This documentation provides comprehensive coverage of Ktor Server Core functionality. Use the linked sub-documents for detailed information about specific capabilities and advanced usage patterns.