0
# Request Building
1
2
Type-safe DSL for building and executing HTTP requests with all standard HTTP methods, URL configuration, headers, and body content.
3
4
## Capabilities
5
6
### Generic Request Functions
7
8
Core request building and execution functions supporting all HTTP methods.
9
10
```kotlin { .api }
11
/**
12
* Executes an HttpClient's request with the parameters specified using builder.
13
*/
14
suspend fun HttpClient.request(
15
builder: HttpRequestBuilder = HttpRequestBuilder()
16
): HttpResponse
17
18
/**
19
* Executes an HttpClient's request with the parameters specified in block.
20
*/
21
suspend fun HttpClient.request(block: HttpRequestBuilder.() -> Unit): HttpResponse
22
23
/**
24
* Executes an HttpClient's request with the urlString and the parameters configured in block.
25
*/
26
suspend fun HttpClient.request(
27
urlString: String,
28
block: HttpRequestBuilder.() -> Unit = {}
29
): HttpResponse
30
31
/**
32
* Executes an HttpClient's request with the url and the parameters configured in block.
33
*/
34
suspend fun HttpClient.request(
35
url: Url,
36
block: HttpRequestBuilder.() -> Unit = {}
37
): HttpResponse
38
39
/**
40
* Prepares an HttpClient's request with the parameters specified using builder.
41
*/
42
suspend fun HttpClient.prepareRequest(
43
builder: HttpRequestBuilder = HttpRequestBuilder()
44
): HttpStatement
45
46
/**
47
* Prepares an HttpClient's request with the parameters specified using block.
48
*/
49
suspend fun HttpClient.prepareRequest(block: HttpRequestBuilder.() -> Unit): HttpStatement
50
```
51
52
**Usage Examples:**
53
54
```kotlin
55
import io.ktor.client.*
56
import io.ktor.client.request.*
57
import io.ktor.http.*
58
59
val client = HttpClient()
60
61
// Using builder
62
val builder = HttpRequestBuilder().apply {
63
method = HttpMethod.Get
64
url("https://api.example.com/users")
65
headers["Authorization"] = "Bearer token"
66
}
67
val response1 = client.request(builder)
68
69
// Using DSL block
70
val response2 = client.request {
71
method = HttpMethod.Post
72
url("https://api.example.com/users")
73
contentType(ContentType.Application.Json)
74
setBody("""{"name": "John"}""")
75
}
76
77
// Using URL string
78
val response3 = client.request("https://api.example.com/users") {
79
method = HttpMethod.Get
80
headers["Accept"] = "application/json"
81
}
82
83
// Prepared request (reusable)
84
val statement = client.prepareRequest {
85
method = HttpMethod.Get
86
url("https://api.example.com/users/{id}")
87
}
88
```
89
90
### HTTP Method Convenience Functions
91
92
Convenience functions for all standard HTTP methods with multiple overloads.
93
94
```kotlin { .api }
95
// GET requests
96
suspend fun HttpClient.get(builder: HttpRequestBuilder): HttpResponse
97
suspend fun HttpClient.get(block: HttpRequestBuilder.() -> Unit): HttpResponse
98
suspend fun HttpClient.get(
99
urlString: String,
100
block: HttpRequestBuilder.() -> Unit = {}
101
): HttpResponse
102
103
// POST requests
104
suspend fun HttpClient.post(builder: HttpRequestBuilder): HttpResponse
105
suspend fun HttpClient.post(block: HttpRequestBuilder.() -> Unit): HttpResponse
106
suspend fun HttpClient.post(
107
urlString: String,
108
block: HttpRequestBuilder.() -> Unit = {}
109
): HttpResponse
110
111
// PUT requests
112
suspend fun HttpClient.put(builder: HttpRequestBuilder): HttpResponse
113
suspend fun HttpClient.put(block: HttpRequestBuilder.() -> Unit): HttpResponse
114
suspend fun HttpClient.put(
115
urlString: String,
116
block: HttpRequestBuilder.() -> Unit = {}
117
): HttpResponse
118
119
// DELETE requests
120
suspend fun HttpClient.delete(builder: HttpRequestBuilder): HttpResponse
121
suspend fun HttpClient.delete(block: HttpRequestBuilder.() -> Unit): HttpResponse
122
suspend fun HttpClient.delete(
123
urlString: String,
124
block: HttpRequestBuilder.() -> Unit = {}
125
): HttpResponse
126
127
// PATCH requests
128
suspend fun HttpClient.patch(builder: HttpRequestBuilder): HttpResponse
129
suspend fun HttpClient.patch(block: HttpRequestBuilder.() -> Unit): HttpResponse
130
suspend fun HttpClient.patch(
131
urlString: String,
132
block: HttpRequestBuilder.() -> Unit = {}
133
): HttpResponse
134
135
// HEAD requests
136
suspend fun HttpClient.head(builder: HttpRequestBuilder): HttpResponse
137
suspend fun HttpClient.head(block: HttpRequestBuilder.() -> Unit): HttpResponse
138
suspend fun HttpClient.head(
139
urlString: String,
140
block: HttpRequestBuilder.() -> Unit = {}
141
): HttpResponse
142
143
// OPTIONS requests
144
suspend fun HttpClient.options(builder: HttpRequestBuilder): HttpResponse
145
suspend fun HttpClient.options(block: HttpRequestBuilder.() -> Unit): HttpResponse
146
suspend fun HttpClient.options(
147
urlString: String,
148
block: HttpRequestBuilder.() -> Unit = {}
149
): HttpResponse
150
```
151
152
**Usage Examples:**
153
154
```kotlin
155
// Simple GET request
156
val response = client.get("https://api.example.com/users")
157
158
// POST with JSON body
159
val postResponse = client.post("https://api.example.com/users") {
160
contentType(ContentType.Application.Json)
161
setBody("""{"name": "Alice", "email": "alice@example.com"}""")
162
}
163
164
// PUT with custom headers
165
val putResponse = client.put("https://api.example.com/users/123") {
166
headers {
167
append(HttpHeaders.Authorization, "Bearer $token")
168
append(HttpHeaders.Accept, "application/json")
169
}
170
contentType(ContentType.Application.Json)
171
setBody(userData)
172
}
173
174
// DELETE request
175
val deleteResponse = client.delete("https://api.example.com/users/123") {
176
headers["Authorization"] = "Bearer $token"
177
}
178
```
179
180
### Prepared Request Functions
181
182
Functions for creating reusable prepared requests for all HTTP methods.
183
184
```kotlin { .api }
185
// Prepared requests for all HTTP methods
186
suspend fun HttpClient.prepareGet(builder: HttpRequestBuilder): HttpStatement
187
suspend fun HttpClient.prepareGet(block: HttpRequestBuilder.() -> Unit): HttpStatement
188
suspend fun HttpClient.prepareGet(
189
urlString: String,
190
block: HttpRequestBuilder.() -> Unit = {}
191
): HttpStatement
192
193
suspend fun HttpClient.preparePost(builder: HttpRequestBuilder): HttpStatement
194
suspend fun HttpClient.preparePost(block: HttpRequestBuilder.() -> Unit): HttpStatement
195
suspend fun HttpClient.preparePost(
196
urlString: String,
197
block: HttpRequestBuilder.() -> Unit = {}
198
): HttpStatement
199
200
// Similar patterns for PUT, DELETE, PATCH, HEAD, OPTIONS
201
suspend fun HttpClient.preparePut(builder: HttpRequestBuilder): HttpStatement
202
suspend fun HttpClient.prepareDelete(builder: HttpRequestBuilder): HttpStatement
203
suspend fun HttpClient.preparePatch(builder: HttpRequestBuilder): HttpStatement
204
suspend fun HttpClient.prepareHead(builder: HttpRequestBuilder): HttpStatement
205
suspend fun HttpClient.prepareOptions(builder: HttpRequestBuilder): HttpStatement
206
```
207
208
**Usage Examples:**
209
210
```kotlin
211
// Prepare reusable requests
212
val getUserStatement = client.prepareGet("https://api.example.com/users/{id}")
213
val updateUserStatement = client.preparePut("https://api.example.com/users/{id}") {
214
contentType(ContentType.Application.Json)
215
}
216
217
// Execute prepared requests multiple times
218
val user1 = getUserStatement.execute { response ->
219
// Process response
220
response.bodyAsText()
221
}
222
223
val user2 = getUserStatement.execute { response ->
224
// Different processing
225
response.body<User>()
226
}
227
```
228
229
### HttpRequestBuilder Class
230
231
Mutable request configuration builder with DSL support for all request parameters.
232
233
```kotlin { .api }
234
/**
235
* HttpRequestBuilder is used to build HttpRequest instances
236
*/
237
class HttpRequestBuilder {
238
/** URL configuration */
239
var url: URLBuilder
240
241
/** HTTP method (GET by default) */
242
var method: HttpMethod = HttpMethod.Get
243
244
/** Headers configuration */
245
var headers: HeadersBuilder
246
247
/** Request body content */
248
var body: Any = EmptyContent
249
250
/** Body type information for serialization */
251
var bodyType: TypeInfo?
252
253
/** Execution context for cancellation */
254
var executionContext: Job
255
256
/** Request-specific attributes */
257
var attributes: Attributes
258
259
/**
260
* Configure URL using URLBuilder DSL
261
*/
262
fun url(block: URLBuilder.(URLBuilder) -> Unit)
263
264
/**
265
* Set URL from string
266
*/
267
fun url(urlString: String)
268
269
/**
270
* Set URL from Url object
271
*/
272
fun url(url: Url)
273
274
/**
275
* Build immutable HttpRequestData
276
*/
277
fun build(): HttpRequestData
278
279
/**
280
* Configure attributes
281
*/
282
fun setAttributes(block: Attributes.() -> Unit)
283
284
/**
285
* Copy configuration from another builder
286
*/
287
fun takeFrom(builder: HttpRequestBuilder): HttpRequestBuilder
288
289
/**
290
* Set engine capability
291
*/
292
fun <T> setCapability(key: HttpClientEngineCapability<T>, capability: T)
293
294
/**
295
* Get engine capability
296
*/
297
fun <T> getCapabilityOrNull(key: HttpClientEngineCapability<T>): T?
298
}
299
```
300
301
**Usage Examples:**
302
303
```kotlin
304
import io.ktor.client.request.*
305
import io.ktor.http.*
306
307
// Build request step by step
308
val builder = HttpRequestBuilder().apply {
309
method = HttpMethod.Post
310
url("https://api.example.com/users")
311
312
// Configure headers
313
headers {
314
append(HttpHeaders.ContentType, "application/json")
315
append(HttpHeaders.Authorization, "Bearer $token")
316
}
317
318
// Set body
319
setBody("""{"name": "John", "email": "john@example.com"}""")
320
321
// Configure attributes
322
attributes.put(AttributeKey("RequestId"), "req-123")
323
}
324
325
// URL configuration
326
builder.url {
327
protocol = URLProtocol.HTTPS
328
host = "api.example.com"
329
port = 443
330
path("users", "create")
331
parameters.append("format", "json")
332
}
333
334
// Build immutable request data
335
val requestData = builder.build()
336
```
337
338
### HttpRequestData Class
339
340
Immutable request data representing a fully configured HTTP request.
341
342
```kotlin { .api }
343
/**
344
* Immutable HTTP request data
345
*/
346
data class HttpRequestData(
347
val url: Url,
348
val method: HttpMethod,
349
val headers: Headers,
350
val body: OutgoingContent,
351
val executionContext: Job,
352
val attributes: Attributes
353
)
354
```
355
356
### Request Builder Utility Functions
357
358
Additional utility functions for creating and configuring request builders.
359
360
```kotlin { .api }
361
/**
362
* Creates an HttpRequestBuilder and configures it using block.
363
*/
364
fun request(block: HttpRequestBuilder.() -> Unit): HttpRequestBuilder
365
```
366
367
**Usage Examples:**
368
369
```kotlin
370
// Create configured builder
371
val builder = request {
372
method = HttpMethod.Get
373
url("https://api.example.com/users")
374
headers["Accept"] = "application/json"
375
}
376
377
// Use with client
378
val response = client.request(builder)
379
```
380
381
### URL Configuration
382
383
Comprehensive URL building capabilities with type-safe DSL.
384
385
```kotlin { .api }
386
/**
387
* Configure URL using URLBuilder DSL
388
*/
389
fun HttpRequestBuilder.url(block: URLBuilder.() -> Unit)
390
391
/**
392
* Set URL from string
393
*/
394
fun HttpRequestBuilder.url(urlString: String)
395
396
/**
397
* Set URL from Url object
398
*/
399
fun HttpRequestBuilder.url(url: Url)
400
401
/**
402
* Configure URL with individual components
403
*/
404
fun HttpRequestBuilder.url(
405
scheme: String = "http",
406
host: String = "localhost",
407
port: Int = DEFAULT_PORT,
408
path: String = "/",
409
block: URLBuilder.() -> Unit = {}
410
)
411
```
412
413
**Usage Examples:**
414
415
```kotlin
416
// URL from string
417
client.get("https://api.example.com/users/123")
418
419
// URL with DSL
420
client.get {
421
url {
422
protocol = URLProtocol.HTTPS
423
host = "api.example.com"
424
port = 443
425
path("users", "123")
426
parameters {
427
append("include", "profile")
428
append("format", "json")
429
}
430
fragment = "details"
431
}
432
}
433
434
// URL with components
435
client.get {
436
url(
437
scheme = "https",
438
host = "api.example.com",
439
port = 443,
440
path = "/users/123"
441
) {
442
parameters.append("include", "profile")
443
}
444
}
445
```
446
447
### Headers Configuration
448
449
Type-safe header configuration with builder pattern.
450
451
```kotlin { .api }
452
/**
453
* Configure headers using HeadersBuilder DSL
454
*/
455
fun HttpRequestBuilder.headers(block: HeadersBuilder.() -> Unit): HeadersBuilder
456
457
/**
458
* Set content type header
459
*/
460
fun HttpRequestBuilder.contentType(contentType: ContentType)
461
462
/**
463
* Set accept header
464
*/
465
fun HttpRequestBuilder.accept(contentType: ContentType)
466
467
/**
468
* Set user agent header
469
*/
470
fun HttpRequestBuilder.userAgent(userAgent: String)
471
```
472
473
**Usage Examples:**
474
475
```kotlin
476
client.post("https://api.example.com/users") {
477
// Content type shortcut
478
contentType(ContentType.Application.Json)
479
480
// Accept header
481
accept(ContentType.Application.Json)
482
483
// Custom headers
484
headers {
485
append(HttpHeaders.Authorization, "Bearer $token")
486
append(HttpHeaders.UserAgent, "MyApp/1.0")
487
append("X-Custom-Header", "value")
488
}
489
490
setBody(userData)
491
}
492
```
493
494
### Request Body Configuration
495
496
Flexible request body configuration supporting various content types.
497
498
```kotlin { .api }
499
/**
500
* Set request body content
501
*/
502
fun HttpRequestBuilder.setBody(body: Any)
503
504
/**
505
* Set typed request body with type information
506
*/
507
fun HttpRequestBuilder.setBody(body: Any, bodyType: TypeInfo)
508
```
509
510
**Usage Examples:**
511
512
```kotlin
513
// String body
514
client.post("https://api.example.com/users") {
515
contentType(ContentType.Application.Json)
516
setBody("""{"name": "John"}""")
517
}
518
519
// Object body (requires serialization plugin)
520
client.post("https://api.example.com/users") {
521
contentType(ContentType.Application.Json)
522
setBody(User(name = "John", email = "john@example.com"))
523
}
524
525
// ByteArray body
526
client.post("https://api.example.com/upload") {
527
contentType(ContentType.Image.PNG)
528
setBody(imageBytes)
529
}
530
531
// Form data
532
client.post("https://api.example.com/form") {
533
setBody(FormDataContent(Parameters.build {
534
append("name", "John")
535
append("email", "john@example.com")
536
}))
537
}
538
```