New to Ktor here is the breakdown- Developer's Commute

In this newsletter I try to breakdown the basics of Ktor and give me coding motivation

Good Morning, It’s your captain speaking. Welcome aboard the Developer’s Commute. Today I have special for you. We are adding a new section to our ship called “Code Philosophy” which will be a newsletter that will distil what I have learned on my job today. I hope you are ready to learn.

Code Philosophy

Breaking down Ktor Basics

In my company, I am currently working on an app that is already written on a native Android platform. They want to me switch it to Kotlin Multiplatform so my job has been learning Ktor and building a clone of the app.

Overall, it's a good learning experience trying to contribute to a production level as well as learning a new technology. If you ask me it's my dream come true. I love solving problems, especially complicated ones and I have got my hands on one of them. You don’t have to be sad. I have got something for you as well.

I am introducing this new part of my newsletter where I distil whatever I learn on a day-to-day basis on my job. I will try to give you something every day, whether it is small or big. I will try to be consistent and give some real value. I hope you enjoy learning with your captain. So, welcome to the Developer’s Commute.

Today in the Daily Code Philosophy I will try to break down Ktor for you. Let's get started.

Introduction to Ktor

→ Ktor is a multiplatform Asynchronous HTTP client which uses different plugins to extend its functionalities

→ We first build an HTTP client and then add plugins to it. That forms the basis of Ktor.

→ Depending on our platform we decide the engine for the Ktor like Android, IOS, Linux, windows etc.

→ Simple KTOR request looks like this

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

suspend fun main() { 
    val client = HttpClient(CIO)
    val response: HttpResponse = client.get("https://ktor.io/")
    println(response.status)
    client.close()
}

REPONSE-> 200OK 
With Explanation:


import io.ktor.client.* -> IMPORTS
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
import io.ktor.client.statement.*

suspend fun main() { -> A SUSPEND FUNCTION BECAUSE IT IS A NETWORK REQUEST

    val client = HttpClient(CIO) -> CALLING A HTTP CLIENT ON THE ENGINE CIO

    val response: HttpResponse = client.get("<https://ktor.io/>")-> CALLING A SIMPLE GET REQUEST AND FILLING VAL WITH THE RESPONSE

    println(response.status)-> PRINTING THE STATUS OF THE RESPONSE

    client.close()-> CLOSES THE HTTP CLIENT

}

REPONSE-> 200OK -> RESPONSE FROM THE NETWORK REQUEST
  • Here we use HttpClient to do a network call → It is a base class that allows us to configure our network requests

  • CIO is a coroutine IO engine

  • We can use different Engines based on where we are using KTOR like Android, JVM, curl etc

  • It is supported on multiple platforms → Android, IOS, JS, Linux, windows etc

  • If you call the HttpClient without any argument the Ktor will choose the engine automatically

Understanding Dependencies

Must add dependencies for KTOR→

  • ktor-client-core

    ktor-client-core contains core Ktor client functionality.

  • Engine dependency

    Engines are used to process network requests. Note that a specific platform may require a specific engine that processes network requests.

  • (Optional) Plugin dependency

    Plugins are used to extend the client with a specific functionality.

  • These are the three types of dependencies that you might need while using Ktor

    • If you want to configure the engine you are using then you can do that in this way:

    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    
    val client = HttpClient(CIO) {
        engine {
            // Configure an engine
        }
    }
    
    • We can install different plugins inside our HttpClient to extend our functionalities:

    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    import io.ktor.client.plugins.logging.*
    
    val client = HttpClient(CIO) {
        install(Logging)
    }
    
    • Also you can do configuration inside of the plugins like this :

    runBlocking {
        val client = HttpClient(CIO) {
            install(Logging) {
                logger = Logger.DEFAULT
                level = LogLevel.HEADERS
                filter { request ->
                    request.url.host.contains("ktor.io")
                }
                sanitizeHeader { header -> header == HttpHeaders.Authorization }
    
    • To free up the space for threads and coroutines call

    client.close()
    
    • We can use get, post, etc requests to get responses from the API and receive them in the JSON form

      val response: HttpResponse = client.get("<https://ktor.io/>")

This was the simple breakdown of the Ktor Client side. I hope enjoyed a brief overview. I will go deeper into this topic over my next few newsletters. I hope you enjoyed your journey on Developer’s Commute.

Developer Motivation

Keep on Learning

Goodbye Fellow Developer

Over and Out Passenger. I hope you enjoyed this journey

I hope you enjoyed this Developer’s Commute. Thank you for joining me.

Your Captain- Hitesh Kohli