CodeBlanks Logo Icon CodeBlanks

GET

Learn GET requests with client.get.

GET request

A GET request fetches a resource from the server. In Ktor you make it with client.get(url), which returns an HttpResponse.

Example: val response = client.get("https://api.example.com/users"). You read the body with response.body<String>(). Query parameters are added via url { parameters.append("id", "1") }. GET is used to read data; it carries no body. The status code is read from response.status.

Query parameters

To add a query parameter to a GET request, use the url block. Inside it you append key-value pairs with parameters.append.

Example: client.get("https://api.example.com/users") { url { parameters.append("page", "1") } }. This call automatically extends the URL with ?page=1. To add more parameters, call append repeatedly. Building the URL by hand is discouraged; the block keeps the code readable and handles escaping automatically.

Practice Make a GET request and print

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

Starter code

Main.kt
// GET request
// 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 sent")
    client.close()
}

Expected output

Request sent

Questions and answers

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

1 Match GET parts

Term Meaning
client.get Sends request
HttpResponse Return type
.body() Gets body
url Address

2 What does client.get(url) return?

  • Int
  • String
  • HttpResponse Correct answer
  • Unit

Explanation: GET returns an HttpResponse.

3 Complete the body call

Question
val response = client.get(url)
val body: String = response.____()
Answer
val response = client.get(url)
val body: String = response.body()

Explanation: answer: body. response.body() gives the body.

All lessons in Advanced