0
# Request Processing
1
2
Request handling functionality for accessing request properties, headers, parameters, cookies, and converting request content to Kotlin types with full type safety.
3
4
## Capabilities
5
6
### Application Request
7
8
Abstract base class for HTTP requests providing access to request properties, headers, and content processing pipeline.
9
10
```kotlin { .api }
11
/**
12
* Interface for HTTP requests
13
*/
14
interface ApplicationRequest {
15
/** The application call this request belongs to */
16
val call: ApplicationCall
17
/** Pipeline for processing request content */
18
val pipeline: ApplicationReceivePipeline
19
/** URL query parameters */
20
val queryParameters: Parameters
21
/** Raw query parameters without decoding */
22
val rawQueryParameters: Parameters
23
/** Request headers */
24
val headers: Headers
25
/** Connection information */
26
val local: RequestConnectionPoint
27
/** Request cookies */
28
val cookies: RequestCookies
29
/** HTTP method (GET, POST, etc.) */
30
val httpMethod: HttpMethod
31
/** Request URI */
32
val uri: String
33
/** HTTP version */
34
val httpVersion: String
35
}
36
```
37
38
### Content Receiving
39
40
Type-safe functions for receiving and converting request content to specific Kotlin types using reified generics.
41
42
```kotlin { .api }
43
/**
44
* Receives and converts request content to specified type
45
* @param T - Target type for content conversion
46
* @return Converted content instance
47
* @throws ContentTransformationException if conversion fails
48
*/
49
suspend inline fun <reified T : Any> ApplicationCall.receive(): T
50
51
/**
52
* Receives request content that may be null
53
* @param T - Target type for content conversion
54
* @return Converted content instance or null
55
*/
56
suspend inline fun <reified T : Any> ApplicationCall.receiveNullable(): T?
57
58
/**
59
* Receives request content as plain text
60
* @return Request body as String
61
*/
62
suspend fun ApplicationCall.receiveText(): String
63
64
/**
65
* Receives form parameters from request body
66
* @return Parameters from form data
67
*/
68
suspend fun ApplicationCall.receiveParameters(): Parameters
69
70
/**
71
* Receives request content as byte array
72
* @return Request body as ByteArray
73
*/
74
suspend fun ApplicationCall.receiveBytes(): ByteArray
75
76
/**
77
* Receives multipart form data
78
* @return MultiPartData for processing file uploads and form fields
79
*/
80
suspend fun ApplicationCall.receiveMultipart(): MultiPartData
81
82
/**
83
* Receives content from a specific channel
84
* @param T - Target type
85
* @return Received content
86
*/
87
suspend inline fun <reified T : Any> ApplicationCall.receiveChannel(): T
88
```
89
90
### Request Properties
91
92
Access to various request properties including parameters, headers, cookies, and connection information.
93
94
```kotlin { .api }
95
/**
96
* Connection information for requests
97
*/
98
interface RequestConnectionPoint {
99
/** Request scheme (http, https) */
100
val scheme: String
101
/** Request version (HTTP/1.1, HTTP/2) */
102
val version: String
103
/** Server port */
104
val port: Int
105
/** Server host */
106
val host: String
107
/** Client/remote host */
108
val remoteHost: String
109
/** Request URI */
110
val uri: String
111
/** Request method */
112
val method: HttpMethod
113
}
114
115
/**
116
* Interface for accessing request cookies
117
*/
118
interface RequestCookies {
119
/** Get cookie value by name */
120
operator fun get(name: String): String?
121
/** Get all cookies as map */
122
fun rawCookies(): Map<String, String>
123
}
124
125
/**
126
* HTTP method enumeration
127
*/
128
enum class HttpMethod(val value: String) {
129
GET("GET"),
130
POST("POST"),
131
PUT("PUT"),
132
DELETE("DELETE"),
133
PATCH("PATCH"),
134
HEAD("HEAD"),
135
OPTIONS("OPTIONS")
136
}
137
138
/** Extension to access HTTP method from call */
139
val ApplicationCall.httpMethod: HttpMethod get() = request.httpMethod
140
141
/** Extension to access request URI from call */
142
val ApplicationCall.uri: String get() = request.uri
143
```
144
145
### Request Pipeline
146
147
Pipeline system for processing and transforming incoming request content through interceptor chains.
148
149
```kotlin { .api }
150
/**
151
* Pipeline for processing incoming request content
152
*/
153
class ApplicationReceivePipeline : Pipeline<Any, ApplicationCall> {
154
companion object {
155
/** Transform phase for content transformation */
156
val Transform: PipelinePhase = PipelinePhase("Transform")
157
/** After phase for post-processing */
158
val After: PipelinePhase = PipelinePhase("After")
159
}
160
}
161
162
/**
163
* Type registry for content conversion
164
*/
165
class ContentConverter {
166
/** Convert content to target type */
167
suspend fun convertForReceive(context: PipelineContext<Any, ApplicationCall>): Any?
168
}
169
```
170
171
### Parameter Access
172
173
Utilities for accessing URL parameters, query parameters, and form parameters with type conversion.
174
175
```kotlin { .api }
176
/**
177
* Interface for parameter collections
178
*/
179
interface Parameters {
180
/** Get single parameter value */
181
operator fun get(name: String): String?
182
/** Get all values for parameter */
183
fun getAll(name: String): List<String>?
184
/** Get all parameter names */
185
fun names(): Set<String>
186
/** Check if parameters are empty */
187
fun isEmpty(): Boolean
188
/** Check if parameter exists */
189
fun contains(name: String): Boolean
190
/** Check if parameter has specific value */
191
fun contains(name: String, value: String): Boolean
192
/** Iterate over parameters */
193
fun forEach(body: (String, List<String>) -> Unit)
194
}
195
196
/** Access to URL path parameters */
197
val ApplicationCall.pathParameters: Parameters get() = parameters
198
199
/** Access to query parameters */
200
val ApplicationCall.queryParameters: Parameters get() = request.queryParameters
201
202
/** Utility extensions for parameter conversion */
203
fun Parameters.getOrFail(name: String): String =
204
get(name) ?: throw MissingRequestParameterException(name)
205
206
fun Parameters.getInt(name: String): Int? = get(name)?.toIntOrNull()
207
fun Parameters.getLong(name: String): Long? = get(name)?.toLongOrNull()
208
fun Parameters.getBoolean(name: String): Boolean? = get(name)?.toBooleanStrictOrNull()
209
```
210
211
**Usage Examples:**
212
213
```kotlin
214
import io.ktor.server.application.*
215
import io.ktor.server.request.*
216
import io.ktor.server.response.*
217
import io.ktor.server.routing.*
218
219
// Receiving JSON content
220
data class User(val name: String, val email: String, val age: Int)
221
222
routing {
223
post("/users") {
224
val user = call.receive<User>()
225
// Process user
226
call.respond(HttpStatusCode.Created, user)
227
}
228
229
// Receiving form parameters
230
post("/login") {
231
val params = call.receiveParameters()
232
val username = params["username"] ?: throw BadRequestException("Missing username")
233
val password = params["password"] ?: throw BadRequestException("Missing password")
234
235
// Authenticate user
236
call.respondText("Login successful")
237
}
238
239
// Receiving plain text
240
post("/webhook") {
241
val payload = call.receiveText()
242
// Process webhook payload
243
call.respond(HttpStatusCode.OK)
244
}
245
}
246
247
// Accessing request properties
248
routing {
249
get("/info") {
250
val method = call.request.httpMethod.value
251
val uri = call.request.uri
252
val userAgent = call.request.headers["User-Agent"]
253
val host = call.request.local.host
254
255
call.respondText("Method: $method, URI: $uri, User-Agent: $userAgent, Host: $host")
256
}
257
258
// Path parameters
259
get("/users/{id}") {
260
val userId = call.parameters["id"]?.toIntOrNull()
261
?: throw BadRequestException("Invalid user ID")
262
263
// Fetch user by ID
264
call.respondText("User ID: $userId")
265
}
266
267
// Query parameters
268
get("/search") {
269
val query = call.request.queryParameters["q"]
270
?: throw BadRequestException("Missing query parameter")
271
val limit = call.request.queryParameters.getInt("limit") ?: 10
272
273
// Perform search
274
call.respondText("Searching for: $query (limit: $limit)")
275
}
276
}
277
278
// File upload handling
279
routing {
280
post("/upload") {
281
val multipart = call.receiveMultipart()
282
multipart.forEachPart { part ->
283
when (part) {
284
is PartData.FileItem -> {
285
val fileName = part.originalFileName
286
val bytes = part.streamProvider().readBytes()
287
// Save file
288
}
289
is PartData.FormItem -> {
290
val fieldName = part.name
291
val fieldValue = part.value
292
// Process form field
293
}
294
else -> Unit
295
}
296
part.dispose()
297
}
298
}
299
}
300
```