POST
- Kotlin course
- Advanced
- Lesson 16/83
- 5 min
Learn POST requests with client.post.
POST request
A POST request sends new data to the server. In Ktor you make it with client.post(url); the body is added with setBody.
Example: client.post("https://api.example.com/users") { setBody(newUser) }. Here newUser is a Kotlin object; the ContentNegotiation plugin turns it into JSON. POST creates a new resource; PUT updates an existing one. The response is again an HttpResponse. To set the body type use contentType(ContentType.Application.Json).
Practice Make a POST request and print
Create an HttpClient. Make a POST request with val response = client.post("https://api.example.com/users"). Print println("Sent"). Then close with client.close().
Starter code
// POST request
// write here
import io.ktor.client.*
import io.ktor.client.request.*
fun main() {
}Sample solution
fun main() {
val client = HttpClient()
val response = client.post("https://api.example.com/users")
println("Sent")
client.close()
}Expected output
Sent
Body and Content-Type
To send a body in a POST request use setBody(data). To declare the body type add contentType(ContentType.Application.Json).
If the ContentNegotiation plugin is installed, the Kotlin object is serialized to JSON automatically. Example: client.post(url) { contentType(ContentType.Application.Json); setBody(user) }. The body is UTF-8 encoded; special characters are escaped. The response body is read again with response.body<T>(). Picking the right Content-Type helps the server recognize the body.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the main difference between POST and PUT?
- POST reads, PUT writes
- POST is faster
- PUT only deletes
- POST creates a new resource, PUT updates Correct answer
Explanation: POST creates new, PUT updates.
2 Complete the setBody call
client.post(url) {
____(user)
}
client.post(url) {
setBody(user)
}
Explanation: answer: setBody. The body is added with setBody.
3 Match POST parts
| Term | Meaning |
|---|---|
client.post |
Sends request |
setBody |
Adds body |
contentType |
Sets type |
HttpResponse |
Response type |