or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

client-management.mdengine-system.mdform-data.mdhttp-utilities.mdindex.mdplugin-system.mdrequest-operations.mdresponse-handling.mdrouting-system.mdserver-framework.md

index.mddocs/

0

# Ktor

1

2

Ktor 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.

3

4

## Package Information

5

6

- **Package Name**: ktor

7

- **Package Type**: maven

8

- **Language**: Kotlin

9

- **Installation**: `implementation "io.ktor:ktor-server-netty:3.2.0"` (server) or `implementation "io.ktor:ktor-client-core:3.2.0"` (client)

10

11

## Core Imports

12

13

### Server

14

```kotlin

15

import io.ktor.server.application.*

16

import io.ktor.server.engine.*

17

import io.ktor.server.netty.*

18

import io.ktor.server.routing.*

19

import io.ktor.server.response.*

20

```

21

22

### Client

23

```kotlin

24

import io.ktor.client.*

25

import io.ktor.client.request.*

26

import io.ktor.client.statement.*

27

```

28

29

### Shared

30

```kotlin

31

import io.ktor.http.*

32

import io.ktor.util.*

33

```

34

35

## Basic Usage

36

37

### Server Application

38

```kotlin

39

import io.ktor.server.application.*

40

import io.ktor.server.engine.*

41

import io.ktor.server.netty.*

42

import io.ktor.server.routing.*

43

import io.ktor.server.response.*

44

import io.ktor.http.*

45

46

fun main() {

47

embeddedServer(Netty, port = 8080) {

48

routing {

49

get("/") {

50

call.respondText("Hello, Ktor Server!", ContentType.Text.Plain)

51

}

52

53

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

54

val id = call.parameters["id"]

55

call.respondText("User ID: $id")

56

}

57

}

58

}.start(wait = true)

59

}

60

```

61

62

### HTTP Client

63

```kotlin

64

import io.ktor.client.*

65

import io.ktor.client.request.*

66

import io.ktor.client.statement.*

67

68

suspend fun main() {

69

val client = HttpClient()

70

71

val response: HttpResponse = client.get("https://api.example.com/users")

72

val content: String = response.bodyAsText()

73

74

println(content)

75

client.close()

76

}

77

```

78

79

## Architecture

80

81

Ktor is built around several key architectural components:

82

83

### Server Architecture

84

- **Application**: Central application instance that manages the server lifecycle

85

- **Engine System**: Pluggable server implementations (Netty, CIO, Jetty, Tomcat)

86

- **Routing DSL**: Type-safe routing system with HTTP method support

87

- **Plugin System**: Extensible plugin architecture for features like authentication, CORS, sessions

88

- **Pipeline Architecture**: Request/response processing pipelines with interceptors

89

- **Configuration System**: HOCON and YAML-based configuration support

90

91

### Client Architecture

92

- **HttpClient**: Main client class for making HTTP requests

93

- **Engine System**: Platform-specific HTTP implementations

94

- **Plugin System**: Extensible plugins for timeouts, authentication, serialization

95

- **Pipeline Architecture**: Request and response processing pipelines

96

- **Multiplatform Support**: Shared API with platform-specific implementations

97

98

### Shared Components

99

- **HTTP Utilities**: Status codes, headers, content types, URL building

100

- **I/O System**: Asynchronous I/O primitives and utilities

101

- **Network Layer**: Low-level networking abstractions

102

- **Serialization**: Integration with kotlinx.serialization and other formats

103

104

## Capabilities

105

106

### Server Framework

107

108

Complete server-side web framework for building REST APIs, web applications, and microservices.

109

110

```kotlin { .api }

111

fun main(args: Array<String>) {

112

embeddedServer(

113

factory: ApplicationEngineFactory<*, *>,

114

port: Int = 80,

115

host: String = "0.0.0.0",

116

watchPaths: List<String> = listOf(WORKING_DIRECTORY_PATH),

117

configure: ApplicationEngineEnvironmentBuilder.() -> Unit = {},

118

module: suspend Application.() -> Unit

119

): ApplicationEngine

120

}

121

122

interface Application : ApplicationCallPipeline, CoroutineScope {

123

val engine: ApplicationEngine

124

val environment: ApplicationEnvironment

125

val monitor: Events

126

val attributes: Attributes

127

}

128

```

129

130

[Server Framework](./server-framework.md)

131

132

### HTTP Client

133

134

Multiplatform asynchronous HTTP client for making requests and handling responses.

135

136

```kotlin { .api }

137

expect fun HttpClient(

138

block: HttpClientConfig<*>.() -> Unit = {}

139

): HttpClient

140

141

class HttpClient(

142

val engine: HttpClientEngine,

143

private val userConfig: HttpClientConfig<out HttpClientEngineConfig>

144

) : CoroutineScope, Closeable {

145

val requestPipeline: HttpRequestPipeline

146

val responsePipeline: HttpResponsePipeline

147

val attributes: Attributes

148

fun close()

149

}

150

```

151

152

[HTTP Client](./client-management.md)

153

154

### Routing System

155

156

Type-safe routing DSL for defining HTTP endpoints and handling requests.

157

158

```kotlin { .api }

159

fun Application.routing(configuration: Routing.() -> Unit): Routing

160

161

interface Routing : Route {

162

val parent: Route?

163

val selector: RouteSelector

164

val developmentMode: Boolean

165

val environment: ApplicationEnvironment

166

}

167

168

fun Route.get(

169

path: String = "",

170

body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit

171

): Route

172

173

fun Route.post(

174

path: String = "",

175

body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit

176

): Route

177

```

178

179

[Routing System](./routing-system.md)

180

181

### Plugin System

182

183

Extensible plugin architecture for both server and client functionality.

184

185

```kotlin { .api }

186

interface Plugin<TConfiguration : Any, TPlugin : Any> {

187

val key: AttributeKey<TPlugin>

188

fun install(pipeline: ApplicationCallPipeline, configure: TConfiguration.() -> Unit): TPlugin

189

}

190

191

fun <TConfiguration : Any, TPlugin : Any> Application.install(

192

plugin: Plugin<TConfiguration, TPlugin>,

193

configure: TConfiguration.() -> Unit = {}

194

): TPlugin

195

```

196

197

[Plugin System](./plugin-system.md)

198

199

### Engine Implementations

200

201

Multiple server and client engines for different deployment scenarios and platforms.

202

203

```kotlin { .api }

204

object Netty : ApplicationEngineFactory<NettyApplicationEngine, NettyApplicationEngine.Configuration>

205

object CIO : ApplicationEngineFactory<CIOApplicationEngine, CIOApplicationEngine.Configuration>

206

object Jetty : ApplicationEngineFactory<JettyApplicationEngine, JettyApplicationEngine.Configuration>

207

208

interface HttpClientEngine : CoroutineScope, Closeable {

209

val dispatcher: CoroutineDispatcher

210

val config: HttpClientEngineConfig

211

suspend fun execute(data: HttpRequestData): HttpResponseData

212

}

213

```

214

215

[Engine System](./engine-system.md)

216

217

### HTTP Utilities

218

219

Core HTTP types, utilities, and extensions for working with HTTP protocols.

220

221

```kotlin { .api }

222

enum class HttpMethod(val value: String) {

223

Get("GET"), Post("POST"), Put("PUT"), Delete("DELETE"),

224

Head("HEAD"), Options("OPTIONS"), Patch("PATCH")

225

}

226

227

data class HttpStatusCode(val value: Int, val description: String) {

228

companion object {

229

val OK = HttpStatusCode(200, "OK")

230

val NotFound = HttpStatusCode(404, "Not Found")

231

val InternalServerError = HttpStatusCode(500, "Internal Server Error")

232

}

233

}

234

235

class URLBuilder(

236

protocol: URLProtocol = URLProtocol.HTTP,

237

host: String = "localhost",

238

port: Int = DEFAULT_PORT,

239

user: String? = null,

240

password: String? = null,

241

pathSegments: List<String> = emptyList(),

242

parameters: Parameters = Parameters.Empty,

243

fragment: String = "",

244

trailingQuery: Boolean = false

245

)

246

```

247

248

[HTTP Utilities](./http-utilities.md)

249

250

## Types

251

252

Core types used across the Ktor framework:

253

254

```kotlin { .api }

255

interface ApplicationCall {

256

val application: Application

257

val request: ApplicationRequest

258

val response: ApplicationResponse

259

val parameters: Parameters

260

val attributes: Attributes

261

}

262

263

interface ApplicationRequest {

264

val call: ApplicationCall

265

val pipeline: ApplicationReceivePipeline

266

val queryParameters: Parameters

267

val headers: Headers

268

val cookies: RequestCookies

269

val local: RequestLocal

270

}

271

272

interface ApplicationResponse {

273

val call: ApplicationCall

274

val pipeline: ApplicationSendPipeline

275

val status: HttpStatusCode?

276

val headers: ResponseHeaders

277

val cookies: ResponseCookies

278

}

279

280

class Attributes {

281

fun <T : Any> get(key: AttributeKey<T>): T

282

fun <T : Any> getOrNull(key: AttributeKey<T>): T?

283

fun <T : Any> put(key: AttributeKey<T>, value: T)

284

}

285

286

interface Headers {

287

operator fun get(name: String): String?

288

fun getAll(name: String): List<String>?

289

fun names(): Set<String>

290

fun entries(): Set<Map.Entry<String, List<String>>>

291

fun isEmpty(): Boolean

292

}

293

```