0
# Server Framework
1
2
Complete server-side web framework for building REST APIs, web applications, and microservices with Ktor.
3
4
## Capabilities
5
6
### Embedded Server
7
8
Creates and starts an embedded server with the specified engine and configuration.
9
10
```kotlin { .api }
11
/**
12
* Creates an embedded server with the specified engine factory
13
* @param factory The engine factory to use (Netty, CIO, Jetty, Tomcat)
14
* @param port The port to bind to
15
* @param host The host to bind to
16
* @param watchPaths Paths to watch for reloading
17
* @param configure Configuration block for the server environment
18
* @param module Application module to install
19
* @return Configured ApplicationEngine instance
20
*/
21
fun <TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration> embeddedServer(
22
factory: ApplicationEngineFactory<TEngine, TConfiguration>,
23
port: Int = 80,
24
host: String = "0.0.0.0",
25
watchPaths: List<String> = listOf(WORKING_DIRECTORY_PATH),
26
configure: ApplicationEngineEnvironmentBuilder.() -> Unit = {},
27
module: suspend Application.() -> Unit
28
): TEngine
29
30
/**
31
* Creates an embedded server from environment
32
* @param factory The engine factory to use
33
* @param environment Pre-configured application environment
34
* @return Configured ApplicationEngine instance
35
*/
36
fun <TEngine : ApplicationEngine, TConfiguration : ApplicationEngine.Configuration> embeddedServer(
37
factory: ApplicationEngineFactory<TEngine, TConfiguration>,
38
environment: ApplicationEnvironment
39
): TEngine
40
```
41
42
**Usage Examples:**
43
44
```kotlin
45
import io.ktor.server.engine.*
46
import io.ktor.server.netty.*
47
import io.ktor.server.application.*
48
import io.ktor.server.routing.*
49
import io.ktor.server.response.*
50
51
// Basic embedded server
52
fun main() {
53
embeddedServer(Netty, port = 8080) {
54
routing {
55
get("/") {
56
call.respondText("Hello World!")
57
}
58
}
59
}.start(wait = true)
60
}
61
62
// Custom configuration
63
fun main() {
64
embeddedServer(Netty, port = 8080, host = "127.0.0.1") {
65
// Configure environment
66
developmentMode = true
67
watchPaths = listOf("build")
68
} {
69
// Application module
70
install(Routing) {
71
get("/health") {
72
call.respondText("OK")
73
}
74
}
75
}.start(wait = true)
76
}
77
```
78
79
### Application Class
80
81
Central application instance that manages the server lifecycle and provides access to core functionality.
82
83
```kotlin { .api }
84
/**
85
* Main application interface for Ktor server applications
86
*/
87
public class Application internal constructor(
88
environment: ApplicationEnvironment,
89
developmentMode: Boolean,
90
public var rootPath: String,
91
public val monitor: Events,
92
public val parentCoroutineContext: CoroutineContext,
93
private val engineProvider: () -> ApplicationEngine
94
) : ApplicationCallPipeline, CoroutineScope {
95
96
/**
97
* The engine instance this application is running on
98
*/
99
val engine: ApplicationEngine
100
101
/**
102
* Application environment containing configuration and other resources
103
*/
104
val environment: ApplicationEnvironment
105
106
/**
107
* Event monitor for application lifecycle events
108
*/
109
val monitor: Events
110
111
/**
112
* Application-scoped attributes storage
113
*/
114
val attributes: Attributes
115
116
/**
117
* Parent coroutine context for the application
118
*/
119
override val coroutineContext: CoroutineContext
120
}
121
```
122
123
### Application Environment
124
125
Configuration container and resource provider for Ktor applications.
126
127
```kotlin { .api }
128
/**
129
* Application environment provides access to configuration and other resources
130
*/
131
interface ApplicationEnvironment {
132
/**
133
* Application configuration from config files
134
*/
135
val config: ApplicationConfig
136
137
/**
138
* Logger instance for the application
139
*/
140
val log: Logger
141
142
/**
143
* Development mode flag
144
*/
145
val developmentMode: Boolean
146
147
/**
148
* Application root path
149
*/
150
val rootPath: String
151
152
/**
153
* Class loader for loading application resources
154
*/
155
val classLoader: ClassLoader
156
157
/**
158
* Monitor for application lifecycle events
159
*/
160
val monitor: Events
161
}
162
```
163
164
### Application Call Pipeline
165
166
Core request/response processing pipeline that handles HTTP calls.
167
168
```kotlin { .api }
169
/**
170
* Base class for applications and routes that provides call processing pipeline
171
*/
172
open class ApplicationCallPipeline(
173
val developmentMode: Boolean = false,
174
val environment: ApplicationEnvironment? = null
175
) : Pipeline<Unit, ApplicationCall> {
176
177
/**
178
* Pipeline for processing incoming calls
179
*/
180
val call: PipelinePhase = PipelinePhase("Call")
181
182
/**
183
* Interceptors for handling specific functionality
184
*/
185
fun intercept(
186
phase: PipelinePhase,
187
block: suspend PipelineContext<Unit, ApplicationCall>.(Unit) -> Unit
188
)
189
}
190
```
191
192
### Application Configuration
193
194
Configuration system supporting HOCON and YAML formats.
195
196
```kotlin { .api }
197
/**
198
* Application configuration interface
199
*/
200
interface ApplicationConfig {
201
/**
202
* Get property value by path
203
*/
204
fun property(path: String): ApplicationConfigValue
205
206
/**
207
* Get property value or null if not found
208
*/
209
fun propertyOrNull(path: String): ApplicationConfigValue?
210
211
/**
212
* Get list of property values
213
*/
214
fun configList(path: String): List<ApplicationConfig>
215
216
/**
217
* Get nested configuration
218
*/
219
fun config(path: String): ApplicationConfig
220
221
/**
222
* Check if property exists
223
*/
224
fun hasProperty(path: String): Boolean
225
226
/**
227
* Get all property keys
228
*/
229
fun keys(): Set<String>
230
}
231
232
/**
233
* Configuration value wrapper
234
*/
235
interface ApplicationConfigValue {
236
fun getString(): String
237
fun getList(): List<String>
238
}
239
```
240
241
**Usage Examples:**
242
243
```kotlin
244
// application.conf (HOCON format)
245
/*
246
ktor {
247
application {
248
modules = [ com.example.ApplicationKt.module ]
249
}
250
deployment {
251
port = 8080
252
host = "0.0.0.0"
253
}
254
database {
255
url = "jdbc:postgresql://localhost/mydb"
256
driver = "org.postgresql.Driver"
257
}
258
}
259
*/
260
261
// Using configuration in application
262
fun Application.module() {
263
val dbUrl = environment.config.property("database.url").getString()
264
val dbDriver = environment.config.property("database.driver").getString()
265
266
// Configure database connection
267
connectToDatabase(dbUrl, dbDriver)
268
}
269
```
270
271
### Server Engine Factories
272
273
Built-in server engine implementations for different deployment scenarios.
274
275
```kotlin { .api }
276
/**
277
* Netty engine factory for high-performance applications
278
*/
279
object Netty : ApplicationEngineFactory<NettyApplicationEngine, NettyApplicationEngine.Configuration> {
280
override fun create(
281
environment: ApplicationEnvironment,
282
configure: NettyApplicationEngine.Configuration.() -> Unit
283
): NettyApplicationEngine
284
}
285
286
/**
287
* CIO (Coroutine I/O) engine factory for pure Kotlin implementation
288
*/
289
object CIO : ApplicationEngineFactory<CIOApplicationEngine, CIOApplicationEngine.Configuration> {
290
override fun create(
291
environment: ApplicationEnvironment,
292
configure: CIOApplicationEngine.Configuration.() -> Unit
293
): CIOApplicationEngine
294
}
295
296
/**
297
* Jetty engine factory for servlet container compatibility
298
*/
299
object Jetty : ApplicationEngineFactory<JettyApplicationEngine, JettyApplicationEngine.Configuration> {
300
override fun create(
301
environment: ApplicationEnvironment,
302
configure: JettyApplicationEngine.Configuration.() -> Unit
303
): JettyApplicationEngine
304
}
305
306
/**
307
* Tomcat engine factory for servlet container compatibility
308
*/
309
object Tomcat : ApplicationEngineFactory<TomcatApplicationEngine, TomcatApplicationEngine.Configuration> {
310
override fun create(
311
environment: ApplicationEnvironment,
312
configure: TomcatApplicationEngine.Configuration.() -> Unit
313
): TomcatApplicationEngine
314
}
315
```
316
317
### Application Engine Interface
318
319
Base interface for all server engine implementations.
320
321
```kotlin { .api }
322
/**
323
* Base interface for all application engines
324
*/
325
interface ApplicationEngine {
326
/**
327
* Engine environment
328
*/
329
val environment: ApplicationEnvironment
330
331
/**
332
* Application instance
333
*/
334
val application: Application
335
336
/**
337
* Start the engine
338
*/
339
fun start(wait: Boolean = false): ApplicationEngine
340
341
/**
342
* Stop the engine
343
*/
344
fun stop(gracePeriodMillis: Long, timeoutMillis: Long)
345
346
/**
347
* Engine configuration
348
*/
349
interface Configuration {
350
var parallelism: Int
351
var connectionGroupSize: Int
352
var workerGroupSize: Int
353
var callGroupSize: Int
354
}
355
}
356
```