Ktor is an asynchronous framework for creating microservices, web applications and more.

Overview

ktor-sample

Ktor

Ktor is an asynchronous framework for creating microservices, web applications and more. Written in Kotlin from the ground up.

  • Application.kt
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import com.example.plugins.*

fun main() {
    embeddedServer(Netty, port = 8080, host = "127.0.0.1") {
        configureRouting()
    }.start(wait = true)
}

  • Routing.kt
import io.ktor.routing.*
import io.ktor.application.*
import io.ktor.response.*


fun Application.configureRouting() {

    routing {
        get("/") {
                call.respondText("Hello Ktor!")
            }
    }
}
  • Runs embedded web server on localhost:8080
  • Installs routing and responds with Hello, world! when receiving a GET http request for the root path

==================================================

  • Ktor Request API With PostMan
  • Routing.kt
import io.ktor.routing.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.response.*


fun Application.configureRouting() {

    routing {
        get("/") {
            println("URI: ${call.request.uri}")
            println("Headers: ${call.request.headers.names()}")

            // Request
            println("User-Agent: ${call.request.headers["User-Agent"]}")
            println("Accept: ${call.request.headers["Accept"]}")
            println("Query Params: ${call.request.queryParameters.names()}")
            println("Name: ${call.request.queryParameters["name"]}")
            println("Email: ${call.request.queryParameters["email"]}")


            call.respondText("Hello Ktor!")
        }
    }
}
Put This Url In Postman And Send Request
http://127.0.0.1:8080?name=Your Name&[email protected]
This Is Result After Send Url In Run Application IntelliJ IDEA Ultimate

URI: /?name=YourName&[email protected]
Headers: [User-Agent, Accept, Postman-Token, Host, Accept-Encoding, Connection]
User-Agent: PostmanRuntime/7.28.4
Accept: */*
Query Params: [name, email]
Name: YourName
Email: [email protected]

==================================================

  • Ktor Url Parameters With PostMan

  • Routing.kt

import io.ktor.routing.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.response.*


fun Application.configureRouting() {

    routing {
        
        // Url Parameters
        get("iphones/{page}") {
            val pageNumber = call.parameters["page"]
            call.respondText("Your are no Page number : $pageNumber")
        }
    }
}
Put This Url In Postman And Send Request
http://127.0.0.1:8080/iphones/2

==================================================

  • Ktor Request Body With PostMan

  • build.gradle.kts

plugins {
    application
    kotlin("jvm") version "1.5.31" // or kotlin("multiplatform") or any other kotlin plugin
    kotlin("plugin.serialization") version "1.5.31"
}

dependencies {
    implementation("io.ktor:ktor-serialization:$ktor_version")
}
  • Routing.kt
() println(userInfo) call.respondText("Everything Working Fine!") } } } ">
import io.ktor.routing.*
import io.ktor.application.*
import io.ktor.request.*
import io.ktor.response.*
import kotlinx.serialization.*

fun Application.configureRouting() {

    routing {
        
        // Request Body
        post("/login") {
            val userInfo = call.receive<UserInfo>()
            println(userInfo)
            call.respondText("Everything Working Fine!")
        }
    }
}
@Serializable
data class UserInfo(
    val name:String,
    val email:String
)
  • Application.kt
install(ContentNegotiation){
    json()
}
1- Put This Url In Postman And Send Request
http://127.0.0.1:8080/login

2- select POST

3- In Body choose format JSON and write json code
{
    "name": "YourName",
    "email": "[email protected]"
}
4- Send
This Is Result After Send Url In Run Application IntelliJ IDEA Ultimate

UserInfo(name=YourName, [email protected])

==================================================

  • Ktor Response - Sending JSON Response With PostMan

  • Routing.kt

//GatewayTimeout
call.respondText("Wrong!!!!!!!!!", status = HttpStatusCode.GatewayTimeout)

// OR NotFound
call.respondText("Not Found !!!!!!!!!", status = HttpStatusCode.NotFound)
  • if you want Sending JSON Response To PostMan
@Serializable
data class UserInfo(
    val name:String,
    val email:String
)
    val responseObj = UserInfo("YourName","[email protected]")
    call.respond(responseObj)
In PostMan
Select GET and Put This Url http://127.0.0.1:8080/
and SEND
The Result in PostMan
=======
{
    "name": "YourName",
    "email": "[email protected]"
}

==================================================

  • Ktor Response - Downloading a File

-- Step one

1- First create a New Directory name = files
2- add some photo in file

-- Step Two

  • Routing.kt
        // Ktor Response - Downloading a File
        get("/fileDownload") {
            val file = File("files/pic.png")

            call.response.header(
                HttpHeaders.ContentDisposition,
                ContentDisposition.Attachment.withParameter(
                    ContentDisposition.Parameters.FileName, "pic.png"
                ).toString()
            )
            call.respondFile(file)

        }


        // Ktor Response - Open a File In Browser
        get("/fileOpen") {
            val file = File("files/pic.png")

            call.response.header(
                HttpHeaders.ContentDisposition,
                ContentDisposition.Inline.withParameter(
                    ContentDisposition.Parameters.FileName, "pic.png"
                ).toString()
            )
            call.respondFile(file)

        }
        
You might also like...
Curso microservices kotlin micronaut
Curso microservices kotlin micronaut

Arquitetura de Microserviços Instruções Criando rede no docker: docker network create micronaut-net Criando imagem Postgresql no Docker: docker run -

Sencilla aplicación web para realizar un CRUD usando Ktor y motores de plantillas similar a Laravel con PHP
Sencilla aplicación web para realizar un CRUD usando Ktor y motores de plantillas similar a Laravel con PHP

Servicio web para crear una WEB App usando Kotlin y Kator así como otras tecnologías propuestas por JetBrains.

Live-coding a web server with Ktor

ktor-sample Live-coding a web server with Ktor Ktor is a Kotlin framework dedicated to building asynchronous servers and clients in connected systems.

A Modern Kotlin-Ktor RESTful API example. Connects to a PostgreSQL database and uses Exposed framework for database operations.
A Modern Kotlin-Ktor RESTful API example. Connects to a PostgreSQL database and uses Exposed framework for database operations.

kotlin-ktor-rest-api A Modern Kotlin-Ktor RESTful API example. Connects to a PostgreSQL database and uses Exposed framework for database operations. F

🍓CookHelper - food social network. The Api and Websocket are based on Ktor framework. Dependency injection with Koin library.

CookHelper [ 🚧 Work in Progress 🚧 ] CookHelper is a cross-platform application that will allow you to cook a delicious dish from an existing recipe

Building Web Applications with React and Kotlin JS Hands-On Lab

Building Web Applications with React and Kotlin JS Hands-On Lab This repository is the code corresponding to the hands-on lab Building Web Application

Firebase Authentication plugin for Ktor framework.

Firebase Authentication is a Ktor plugin which verifies requests authorized by a Firebase Auth Id Token.

The WeeBe application is a social media-type app built on Ktor framework

The WeeBe application is a social media-type app built on Ktor framework that allows users to exchange various content connected with mental health, motivation, psychology, and improving oneself. Users can share posts with texts, images, videos, and links, as well as discuss the content in the comment section

KVision allows you to build modern web applications with the Kotlin language

KVision allows you to build modern web applications with the Kotlin language, without any use of HTML, CSS or JavaScript. It gives you a rich hierarchy of ready to use GUI components, which can be used as builder blocks for the application UI.

Owner
mohamed tamer
Android Developer Kotlin & Java
mohamed tamer
Microservices with Ktor and Nomad

Microserviços com Ktor e Nomad Esse projeto é um teste prático de microserviços usando o framework Ktor, o banco de dados Postgres, o orquestrador de

Ederson Ferreira 3 Sep 16, 2022
Webclient-kotlin-sample - An example of using the http web client to promote synchronous and asynchronous https calls

Web Client Consumer Kotlin Sample The project is an example of using the http we

null 1 May 1, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
KTor-Client---Android - The essence of KTor Client for network calls

KTor Client - Android This project encompasses the essence of KTor Client for ne

Mansoor Nisar 2 Jan 18, 2022
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

Oguzhan 18 Apr 21, 2022
This lib is the framework for dependency tasks, specially for the asynchronous tasks.

DependencyTask This lib is the framework for dependency tasks, specially for the asynchronous tasks. Backgroud Image that there is a progress with som

null 1 May 6, 2022
In this Repo i create public apis to serve apps, like muslim apps using Spring, kotlin, and microservices

spring-freelance-apis-kotlin In this Repo i create public apis to serve apps, like muslim apps using Spring, kotlin, and microservices This repo for l

null 6 Feb 13, 2022
Team management service is a production ready and fully tested service that can be used as a template for a microservices development.

team-mgmt-service Description Team management service is a production ready and fully tested service that can be used as a template for a microservice

Albert Llousas Ortiz 18 Oct 10, 2022
A project to learn about Reactive Microservices experimenting with architectures and patterns

reactive-microservices-workshop Copyright © 2021 Aleix Morgadas - Licenced under CC BY-SA 4.0 A project to learn about Reactive Microservices experime

Aleix Morgadas 7 Feb 21, 2022
Proof-of-Concept messaging and "voice over IP" server that uses microservices

bullets THIS IS A WIP PROJECT. Proof-of-Concept messaging and "voice over IP" server that uses microservices. The project uses many technologies. Such

Paulo Elienay II 0 Jan 2, 2022