Convert Figma logo to code with AI

ktorio logoktor

Framework for quickly creating connected applications in Kotlin with minimal effort

12,761
1,039
12,761
162

Top Related Projects

Spring Boot

64,773

Fast, unopinionated, minimalist web framework for node.

66,731

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

77,851

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

33,019

⚡️ Express inspired web framework written in Go

29,410

High performance, minimalist Go web framework

Quick Overview

Ktor is a framework for building asynchronous servers and clients in connected systems using the Kotlin programming language. It provides a flexible and extensible architecture for creating web applications, microservices, and mobile/desktop HTTP clients with minimal effort and maximum performance.

Pros

  • Fully asynchronous and non-blocking, leveraging Kotlin coroutines for high scalability
  • Modular design with a rich ecosystem of plugins for easy customization and extension
  • Cross-platform support, allowing development for JVM, Android, iOS, and JavaScript
  • Strong type safety and concise syntax thanks to Kotlin language features

Cons

  • Steeper learning curve compared to some traditional Java web frameworks
  • Smaller community and ecosystem compared to more established frameworks like Spring
  • Documentation can be inconsistent or lacking in some areas
  • May require more manual configuration compared to opinionated frameworks

Code Examples

  1. Creating a simple HTTP server:
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                call.respondText("Hello, World!")
            }
        }
    }.start(wait = true)
}
  1. Making an HTTP GET request using the Ktor client:
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://api.example.com/data")
    println(response.bodyAsText())
    client.close()
}
  1. Implementing a WebSocket server:
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.websocket.*
import io.ktor.websocket.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(WebSockets)
        routing {
            webSocket("/echo") {
                for (frame in incoming) {
                    if (frame is Frame.Text) {
                        send(Frame.Text("Echo: ${frame.readText()}"))
                    }
                }
            }
        }
    }.start(wait = true)
}

Getting Started

To start using Ktor in your Kotlin project, add the following dependencies to your build.gradle.kts file:

val ktor_version = "2.3.0"
dependencies {
    implementation("io.ktor:ktor-server-core:$ktor_version")
    implementation("io.ktor:ktor-server-netty:$ktor_version")
    implementation("io.ktor:ktor-client-core:$ktor_version")
    implementation("io.ktor:ktor-client-cio:$ktor_version")
}

Then, create a new Kotlin file and start building your application using the examples provided above.

Competitor Comparisons

Spring Boot

Pros of Spring Boot

  • Extensive ecosystem with a wide range of built-in features and integrations
  • Robust documentation and large community support
  • Mature framework with proven track record in enterprise applications

Cons of Spring Boot

  • Steeper learning curve due to its comprehensive nature
  • Heavier footprint and potentially slower startup times
  • More opinionated, which can limit flexibility in certain scenarios

Code Comparison

Spring Boot:

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

Ktor:

fun Application.module() {
    routing {
        get("/hello") {
            call.respondText("Hello, World!")
        }
    }
}

Spring Boot offers a more annotation-driven approach, while Ktor uses a more functional style. Spring Boot's code is more declarative, whereas Ktor's is more explicit in defining the routing structure.

Both frameworks provide concise ways to create web applications, but Ktor's approach may be more appealing to developers who prefer a less magic, more hands-on style of programming. Spring Boot's annotations can make it easier to set up common patterns quickly, but may obscure some of the underlying mechanics.

64,773

Fast, unopinionated, minimalist web framework for node.

Pros of Express

  • Larger ecosystem and community support, with more third-party middleware and plugins available
  • Simpler learning curve for developers familiar with JavaScript and Node.js
  • More mature and battle-tested in production environments

Cons of Express

  • Less type-safe compared to Ktor's Kotlin-based approach
  • Performance can be slower, especially for high-concurrency scenarios
  • Lacks built-in support for coroutines and asynchronous programming patterns

Code Comparison

Express:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

Ktor:

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

fun Application.module() {
    routing {
        get("/") {
            call.respondText("Hello World!")
        }
    }
}

Both frameworks offer simple and concise ways to create routes and handle requests. Express uses a more traditional callback-based approach, while Ktor leverages Kotlin's coroutines for asynchronous programming. Ktor's syntax is more type-safe and structured, whereas Express offers a more flexible and familiar JavaScript style.

66,731

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Pros of Nest

  • Built-in dependency injection and modular architecture
  • Extensive ecosystem with official packages for various integrations
  • Strong TypeScript support with decorators for enhanced developer experience

Cons of Nest

  • Steeper learning curve due to its opinionated structure
  • Potentially higher overhead for simple applications
  • Less flexibility compared to Ktor's lightweight approach

Code Comparison

Nest (TypeScript):

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

Ktor (Kotlin):

routing {
    get("/cats") {
        call.respondText("This action returns all cats")
    }
}

Summary

Nest is a feature-rich framework with a robust ecosystem, ideal for large-scale applications. It offers strong TypeScript support and a structured approach to development. However, it may be overkill for smaller projects and has a steeper learning curve.

Ktor, on the other hand, is lightweight and flexible, making it suitable for both small and large applications. It provides a more straightforward setup but may require additional libraries for certain features that come built-in with Nest.

The choice between Nest and Ktor depends on project requirements, team expertise, and desired level of structure and flexibility in the development process.

77,851

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

Pros of Gin

  • Faster performance and lower memory usage
  • Simpler API with less boilerplate code
  • Larger ecosystem and community support

Cons of Gin

  • Less flexible and extensible architecture
  • Limited built-in features compared to Ktor
  • Primarily focused on HTTP routing, lacking some advanced features

Code Comparison

Gin:

r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{"message": "pong"})
})
r.Run()

Ktor:

embeddedServer(Netty, port = 8080) {
    routing {
        get("/ping") {
            call.respondText("pong", ContentType.Text.Plain)
        }
    }
}.start(wait = true)

Summary

Gin is a lightweight and fast web framework for Go, focusing on simplicity and performance. It excels in routing and basic HTTP handling but may lack some advanced features. Ktor, on the other hand, is a more comprehensive framework for Kotlin, offering greater flexibility and extensibility. While Ktor provides more built-in features, it may have a steeper learning curve and slightly lower performance compared to Gin. The choice between the two depends on the specific project requirements, language preference, and desired balance between simplicity and feature richness.

33,019

⚡️ Express inspired web framework written in Go

Pros of Fiber

  • Extremely fast performance due to its lightweight design and use of Go's concurrency model
  • Simple and expressive API, making it easy for developers to quickly build web applications
  • Built-in support for WebSocket, allowing real-time communication out of the box

Cons of Fiber

  • Less mature ecosystem compared to Ktor, with fewer third-party libraries and extensions
  • Limited built-in features, requiring more manual implementation for complex applications
  • Go-specific, limiting its use to projects written in Go

Code Comparison

Fiber (Go):

app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
    return c.SendString("Hello, World!")
})
app.Listen(":3000")

Ktor (Kotlin):

fun main() {
    embeddedServer(Netty, port = 3000) {
        routing {
            get("/") {
                call.respondText("Hello, World!")
            }
        }
    }.start(wait = true)
}

Both frameworks offer concise and readable syntax for creating simple web applications. Fiber's approach is more function-based, while Ktor uses a DSL-style configuration. The core concepts of routing and handling requests are similar in both frameworks, making it relatively easy for developers to switch between them if needed.

29,410

High performance, minimalist Go web framework

Pros of Echo

  • Simpler and more lightweight framework, easier to get started with
  • Better performance in benchmarks, especially for high-concurrency scenarios
  • More idiomatic Go code, following Go conventions closely

Cons of Echo

  • Less feature-rich compared to Ktor's extensive functionality
  • Smaller community and ecosystem, with fewer plugins and extensions
  • Limited built-in support for websockets and other advanced features

Code Comparison

Echo:

e := echo.New()
e.GET("/", func(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":1323"))

Ktor:

fun main() {
    embeddedServer(Netty, port = 8080) {
        routing {
            get("/") {
                call.respondText("Hello, World!")
            }
        }
    }.start(wait = true)
}

Both frameworks offer concise and readable code for creating a simple HTTP server. Echo's approach is more Go-idiomatic, while Ktor leverages Kotlin's DSL capabilities for a declarative style. Echo's setup is slightly more compact, but Ktor's routing DSL can be more expressive for complex applications.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Ktor logo

Official JetBrains project Maven Central Kotlin Slack channel GitHub License Contribute with Gitpod

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

First add the dependency to your project:

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.ktor:ktor-server-netty:$ktor_version")
}

Then create an Application and install some features:

import io.ktor.server.netty.*
import io.ktor.server.routing.*
import io.ktor.server.application.*
import io.ktor.http.*
import io.ktor.server.response.*
import io.ktor.server.engine.*

fun main(args: Array<String>) {
    embeddedServer(Netty, 8080) {
        routing {
            get("/") {
                call.respondText("Hello, world!", ContentType.Text.Html)
            }
        }
    }.start(wait = true)
}

You also can use Ktor Gradle Plugin to configure bom, run tasks and deployment:

plugins {
    id("io.ktor.plugin") version "2.3.4"
}

dependencies {
    implementation("io.ktor:ktor-server-netty")
}

To run the created application, execute:

./gradlew run
  • Runs embedded web server on localhost:8080
  • Installs routing and responds with Hello, world! when receiving a GET http request for the root path

Start using Ktor

Build your first Kotlin HTTP or RESTful application using Ktor: start.ktor.io

Principles

Unopinionated

Ktor Framework doesn't impose a lot of constraints on what technology a project is going to use – logging, templating, messaging, persistence, serialization, dependency injection, etc. Sometimes it may be required to implement a simple interface, but usually it is a matter of writing a transforming or intercepting function. Features are installed into the application using a unified interception mechanism which allows building arbitrary pipelines.

Ktor Applications can be hosted in any servlet container with Servlet 3.0+ API support such as Tomcat, or standalone using Netty or Jetty. Support for other hosts can be added through the unified hosting API.

Ktor APIs are mostly functions calls with lambdas. Thanks to Kotlin DSL capabilities, the code looks declarative. Application composition is entirely up to the developer's choice – with functions or classes, using dependency injection framework or doing it all manually in the main function.

Asynchronous

The Ktor pipeline machinery and API are utilising Kotlin coroutines to provide easy-to-use asynchronous programming model without making it too cumbersome. All host implementations are using asynchronous I/O facilities to avoid thread blocking.

Testable

Ktor applications can be hosted in a special test environment, which emulates a web server to some extent without actually doing any networking. It provides easy way to test an application without mocking too much stuff, and still achieve good performance while validating application calls. Running integration tests with a real embedded web server are of course possible, too.

JetBrains Product

Ktor is an official JetBrains product and is primarily developed by the team at JetBrains, with contributions from the community.

Documentation

Please visit ktor.io for Quick Start and detailed explanations of features, usage and machinery.

  • Getting started with Gradle
  • Getting started with Maven
  • Getting started with IDEA

Reporting Issues / Support

Please use our issue tracker for filing feature requests and bugs. If you'd like to ask a question, we recommend StackOverflow where members of the team monitor frequently.

There is also community support on the Kotlin Slack Ktor channel

Reporting Security Vulnerabilities

If you find a security vulnerability in Ktor, we kindly request that you reach out to the JetBrains security team via our responsible disclosure process.

Inspirations

Kotlin web frameworks such as Wasabi and Kara, which are currently deprecated.

Contributing

Please see the contribution guide and the Code of conduct before contributing.