A multiplatform asynchronous framework for creating microservices, web applications, and HTTP clients written in Kotlin from the ground up
npx @tessl/cli install tessl/maven-io-ktor--ktor@3.2.0Ktor is a multiplatform asynchronous framework for creating microservices, web applications, and HTTP clients. Written in Kotlin from the ground up, it provides both server-side functionality for building web applications and APIs, as well as a powerful HTTP client for making requests to external services.
implementation "io.ktor:ktor-server-netty:3.2.0" (server) or implementation "io.ktor:ktor-client-core:3.2.0" (client)import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.response.*import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*import io.ktor.http.*
import io.ktor.util.*import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
import io.ktor.http.*
fun main() {
embeddedServer(Netty, port = 8080) {
routing {
get("/") {
call.respondText("Hello, Ktor Server!", ContentType.Text.Plain)
}
get("/users/{id}") {
val id = call.parameters["id"]
call.respondText("User ID: $id")
}
}
}.start(wait = true)
}import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
suspend fun main() {
val client = HttpClient()
val response: HttpResponse = client.get("https://api.example.com/users")
val content: String = response.bodyAsText()
println(content)
client.close()
}Ktor is built around several key architectural components:
Complete server-side web framework for building REST APIs, web applications, and microservices.
fun main(args: Array<String>) {
embeddedServer(
factory: ApplicationEngineFactory<*, *>,
port: Int = 80,
host: String = "0.0.0.0",
watchPaths: List<String> = listOf(WORKING_DIRECTORY_PATH),
configure: ApplicationEngineEnvironmentBuilder.() -> Unit = {},
module: suspend Application.() -> Unit
): ApplicationEngine
}
interface Application : ApplicationCallPipeline, CoroutineScope {
val engine: ApplicationEngine
val environment: ApplicationEnvironment
val monitor: Events
val attributes: Attributes
}Multiplatform asynchronous HTTP client for making requests and handling responses.
expect fun HttpClient(
block: HttpClientConfig<*>.() -> Unit = {}
): HttpClient
class HttpClient(
val engine: HttpClientEngine,
private val userConfig: HttpClientConfig<out HttpClientEngineConfig>
) : CoroutineScope, Closeable {
val requestPipeline: HttpRequestPipeline
val responsePipeline: HttpResponsePipeline
val attributes: Attributes
fun close()
}Type-safe routing DSL for defining HTTP endpoints and handling requests.
fun Application.routing(configuration: Routing.() -> Unit): Routing
interface Routing : Route {
val parent: Route?
val selector: RouteSelector
val developmentMode: Boolean
val environment: ApplicationEnvironment
}
fun Route.get(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
fun Route.post(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): RouteExtensible plugin architecture for both server and client functionality.
interface Plugin<TConfiguration : Any, TPlugin : Any> {
val key: AttributeKey<TPlugin>
fun install(pipeline: ApplicationCallPipeline, configure: TConfiguration.() -> Unit): TPlugin
}
fun <TConfiguration : Any, TPlugin : Any> Application.install(
plugin: Plugin<TConfiguration, TPlugin>,
configure: TConfiguration.() -> Unit = {}
): TPluginMultiple server and client engines for different deployment scenarios and platforms.
object Netty : ApplicationEngineFactory<NettyApplicationEngine, NettyApplicationEngine.Configuration>
object CIO : ApplicationEngineFactory<CIOApplicationEngine, CIOApplicationEngine.Configuration>
object Jetty : ApplicationEngineFactory<JettyApplicationEngine, JettyApplicationEngine.Configuration>
interface HttpClientEngine : CoroutineScope, Closeable {
val dispatcher: CoroutineDispatcher
val config: HttpClientEngineConfig
suspend fun execute(data: HttpRequestData): HttpResponseData
}Core HTTP types, utilities, and extensions for working with HTTP protocols.
enum class HttpMethod(val value: String) {
Get("GET"), Post("POST"), Put("PUT"), Delete("DELETE"),
Head("HEAD"), Options("OPTIONS"), Patch("PATCH")
}
data class HttpStatusCode(val value: Int, val description: String) {
companion object {
val OK = HttpStatusCode(200, "OK")
val NotFound = HttpStatusCode(404, "Not Found")
val InternalServerError = HttpStatusCode(500, "Internal Server Error")
}
}
class URLBuilder(
protocol: URLProtocol = URLProtocol.HTTP,
host: String = "localhost",
port: Int = DEFAULT_PORT,
user: String? = null,
password: String? = null,
pathSegments: List<String> = emptyList(),
parameters: Parameters = Parameters.Empty,
fragment: String = "",
trailingQuery: Boolean = false
)Core types used across the Ktor framework:
interface ApplicationCall {
val application: Application
val request: ApplicationRequest
val response: ApplicationResponse
val parameters: Parameters
val attributes: Attributes
}
interface ApplicationRequest {
val call: ApplicationCall
val pipeline: ApplicationReceivePipeline
val queryParameters: Parameters
val headers: Headers
val cookies: RequestCookies
val local: RequestLocal
}
interface ApplicationResponse {
val call: ApplicationCall
val pipeline: ApplicationSendPipeline
val status: HttpStatusCode?
val headers: ResponseHeaders
val cookies: ResponseCookies
}
class Attributes {
fun <T : Any> get(key: AttributeKey<T>): T
fun <T : Any> getOrNull(key: AttributeKey<T>): T?
fun <T : Any> put(key: AttributeKey<T>, value: T)
}
interface Headers {
operator fun get(name: String): String?
fun getAll(name: String): List<String>?
fun names(): Set<String>
fun entries(): Set<Map.Entry<String, List<String>>>
fun isEmpty(): Boolean
}