CodeBlanks Logo Icon CodeBlanks

Summary - Ktor HTTP

Combine HttpClient, GET and JSON to write an API client.

Summary - Ktor HTTP

This group covered Ktor client, HttpClient, GET, POST and JSON deserialization. These are the foundations of a modern HTTP client.

You open an HttpClient, configure it with plugins, make requests with get and post, and turn the result into an object with body(). Because it is coroutine based you can run concurrent calls without blocking the UI thread. The next group moves to the server side.

Practice Summary: Ktor GET

Create an HttpClient. Make a GET request with val response = client.get("https://api.example.com/users"). Print println("Request ready"). Then close with client.close().

Starter code

Main.kt
// Summary: Ktor GET
// write here
import io.ktor.client.*
import io.ktor.client.request.*

fun main() {
    
}

Sample solution

Main.kt
fun main() {
    val client = HttpClient()
    val response = client.get("https://api.example.com/users")
    println("Request ready")
    client.close()
}

Expected output

Request ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which one is used to send a body in a POST request?

  • getBody
  • setBody Correct answer
  • setUrl
  • setHeader

Explanation: answer: setBody. The body is added with setBody.

2 Match all Ktor client concepts

Term Meaning
HttpClient Client
get GET request
post POST request
@Serializable Class mark
.body() Gets object

All lessons in Advanced