Sling Academy
Home/Kotlin/Making GET and POST Requests with Ktor in Kotlin

Making GET and POST Requests with Ktor in Kotlin

Last updated: December 05, 2024

Ktor is a framework sponsored by JetBrains for building asynchronous servers and clients in connected systems using Kotlin. This article aims to guide you through making GET and POST requests with Ktor client, which is a powerful and flexible HTTP client library that is suitable for both Android applications and web server applications.

Setting Up Ktor Client

To begin, you need to add Ktor client dependencies to your project. Open your build.gradle.kts file and include the following dependencies:

dependencies {
    implementation("io.ktor:ktor-client-core:2.0.0")
    implementation("io.ktor:ktor-client-cio:2.0.0")
    implementation("io.ktor:ktor-client-json:2.0.0")
    implementation("io.ktor:ktor-client-serialization:2.0.0")
}

Make sure you have the necessary versions and that your repositories block includes a reference to the mavenCentral() repository.

Making a GET Request

A GET request is used to retrieve data from a specified resource. You can make a GET request using Ktor client by creating an instance and specifying the endpoint you wish to query. Here is an example:

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*

suspend fun getRequest() {
    val client = HttpClient(CIO)
    try {
        val response: String = client.get("https://jsonplaceholder.typicode.com/todos/1")
        println(response)
    } catch (e: Exception) {
        println("Error on GET request: ${e.message}")
    } finally {
        client.close()
    }
}

In this snippet, we initiate the Ktor client using the CIO engine and perform a GET request. Don't forget to run this asynchronously using Kotlin Coroutines since network operations must not occur on the main thread.

Making a POST Request

POST requests are made to submit data to be processed to a specified resource. In Ktor, creating a POST request can be straightforward as shown below:

import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*

suspend fun postRequest() {
    val client = HttpClient(CIO) {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }

    val postData = PostData(userId = 1, id = null, title = "Foo", body = "Bar")

    try {
        val response: PostData = client.post("https://jsonplaceholder.typicode.com/posts") {
            contentType(ContentType.Application.Json)
            body = postData
        }
        println(response)
    } catch (e: Exception) {
        println("Error on POST request: ${e.message}")
    } finally {
        client.close()
    }
}

data class PostData(val userId: Int, val id: Int?, val title: String, val body: String)

In this example, we define a Kotlin data class PostData to map the request body. We use the KotlinxSerializer to serialize our data as JSON before sending it with the request. Be sure to handle exceptions with a try-catch block to manage errors efficiently.

Conclusions and Best Practices

Ktor client can be an effective tool not only because of its asynchronous nature, but also because it is simple and intuitive. When working with Ktor, always ensure your requests are thread-safe and handle all possible exceptions for improved reliability. Ensure your dependencies are kept up-to-date as Ktor is actively maintained with new features and improvements. Happy coding!

Next Article: Using Ktor for Asynchronous Networking in Kotlin

Previous Article: Setting Up Ktor for HTTP Requests in Kotlin

Series: Networking in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin