Ktor Tutorial
Learn Ktor step by step: 38 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Ktor? Meet Ktor, the coroutine-based Kotlin framework for servers and clients from JetBrains. Learn what it does, how it differs from Spring, and what you will build.
- Project Setup with Gradle Set up a Ktor 3 project with Gradle Kotlin DSL: the Ktor plugin, engine and feature dependencies, source layout, and how install { } configuration blocks work.
- Your First Ktor Server Write and run your first Ktor server: embeddedServer, routing, call.respondText, and a runnable JDK HTTP server stand-in that you can call from the same program.
- Application Modules and Configuration Configure a Ktor server with application.conf or YAML: ports, modules, environment variables, custom settings, and reading config values safely in code.
- How Ktor Handles a Request Follow one HTTP request through a Ktor server: engine, pipeline phases, plugins, routing and the handler, and see why suspend functions scale without blocking threads.
Routing and Requests
- Routing Basics Learn Ktor routing: get, post, put and delete handlers, path templates, wildcards, tail segments, and how a router chooses between competing routes.
- Path and Query Parameters Read path and query parameters in Ktor, convert them to Int and other types safely, handle missing or invalid values with 400 errors, and decode URL escapes.
- Requests and Responses Work with Ktor's ApplicationRequest and ApplicationResponse: read headers, text, form and JSON bodies with receive, and send text, HTML, files and objects with respond.
- Status Codes and Headers Use the right HTTP status codes and headers in Ktor: HttpStatusCode, 201 with Location, 204, 304 and ETag, 405 with Allow, redirects, and caching headers.
- Structured Routing and Resources Organize a growing Ktor API: nested route blocks, extension functions per feature, the Resources plugin for type-safe routes, and serving static files.
Plugins and Serialization
- Plugins and Interceptors Understand Ktor plugins: install built-in ones, scope them to routes, and write custom plugins with createApplicationPlugin, onCall and onCallRespond hooks.
- Content Negotiation and JSON Send and receive JSON in Ktor: install ContentNegotiation, annotate data classes with @Serializable, configure Json, and see how the Accept header picks a format.
- Status Pages and Error Handling Handle errors cleanly in Ktor with the StatusPages plugin: map exceptions to JSON error responses, custom exception classes, status handlers for 404, and safe 500s.
- Request Validation Validate incoming data in Ktor with the RequestValidation plugin: validate blocks, ValidationResult, handling RequestValidationException, and designing helpful error output.
- Logging, CORS and Compression Configure three everyday Ktor plugins: CallLogging with call IDs, CORS rules for browser front ends, and gzip Compression, with a stand-in showing the CORS rules and gzip savings.
Authentication
- Authentication Basics Protect Ktor routes: the Authentication plugin, named providers, HTTP Basic auth, call.principal, 401 challenges, and storing passwords safely with salted hashes.
- Bearer Tokens and JWT Secure a Ktor API with JSON Web Tokens: how a JWT is built and signed, the jwt provider with verifier and validate, issuing tokens at login, expiry and common mistakes.
- Sessions and Cookies Use the Ktor Sessions plugin: cookie-based client sessions, signing and encryption, server-side session storage, session authentication, cookie flags and logout.
- OAuth and Authorization Add Sign in with an identity provider using Ktor's OAuth provider, understand the authorization code flow with state and PKCE, and enforce roles with a route-scoped plugin.
Databases with Exposed
- Exposed Basics - Tables, Transactions and CRUD Connect a Ktor server to a database with JetBrains Exposed. Define tables in the Kotlin DSL, open transactions, and run insert, select, update and delete safely.
- Querying with the Exposed DSL - Where, Joins, Aggregates Write real queries with the Exposed DSL in a Ktor app - conditions, ordering, paging, joins, aggregates and batch inserts - and practise the same ideas in runnable Kotlin.
- Exposed DAO and Relations - Entities, One-to-Many, N+1 Use the Exposed DAO API in a Ktor service - entity classes, property delegates, one-to-many and many-to-many relations, eager loading and the N+1 problem - with runnable Kotlin models.
- Connection Pooling and Migrations for Ktor Apps Configure HikariCP connection pools and Flyway migrations for a Ktor and Exposed app, and learn how pools and versioned migrations work with runnable Kotlin models.
WebSockets and SSE
- WebSockets in Ktor - Sessions, Frames and Echo Server Build two-way real-time features with Ktor WebSockets. Install the plugin, handle text and binary frames, read incoming messages, close sessions cleanly, and practise with runnable Kotlin.
- Server-Sent Events (SSE) in Ktor - Live Streams over HTTP Stream live updates from a Ktor server to the browser with Server-Sent Events. Learn the text/event-stream format, the sse route, reconnects and Last-Event-ID, and compare SSE with WebSockets.
- Broadcasting to Many Clients - Rooms, SharedFlow, Backpressure Fan out messages to many WebSocket or SSE clients in Ktor. Build chat rooms with a connection registry and SharedFlow, handle slow consumers with buffers, and keep shared state thread-safe.
Testing
- Testing Ktor Applications with testApplication Test Ktor routes without opening a network port using testApplication and the test client. Cover status codes, JSON bodies, headers, cookies and error cases, with runnable Kotlin test-host models.
- Testing Ktor with Fakes, Mocks and Real Databases Isolate the data layer when testing Ktor services. Compare fakes, mocks and real databases (H2, Testcontainers), design for testability with interfaces, and test error paths with runnable Kotlin.
- Testing WebSockets, SSE and Concurrent Code in Ktor Test Ktor WebSocket and SSE routes with the test client, and write deterministic tests for coroutine code using runTest, virtual time and Turbine-style flow assertions in runnable Kotlin.
Deployment and Coroutines
- Coroutines in Ktor - Concurrency, Dispatchers and Timeouts Understand how Ktor handles requests with coroutines. Run calls in parallel with async, move blocking work to Dispatchers.IO, add timeouts, handle cancellation, and run background jobs safely.
- Configuration and Environments in Ktor Configure a Ktor server for development, testing and production. Learn application.yaml, environment variable substitution, typed settings, secrets handling and failing fast on bad config.
- Packaging and Deploying Ktor with Docker Package a Ktor server as a fat JAR or distribution, build a small multi-stage Docker image, tune the JVM for containers and understand layer caching, ports, users and health checks.
- Production Readiness for Ktor Servers Prepare a Ktor server for real traffic: health and readiness endpoints, metrics, rate limiting, proxy headers, call IDs, request limits and graceful shutdown that drains in-flight requests.
- The Ktor HTTP Client - Calling Other Services Use the Ktor HTTP client from a server: engines, JSON bodies, timeouts, retries with backoff, error handling, parallel calls and swapping in a fake engine for fast, offline tests.
Projects and Practice
- Project: Build a URL Shortener with Ktor Build a URL shortener step by step: design the API, generate Base62 codes, validate URLs, redirect with 302, count clicks, store links with Exposed and test the routes. Includes a runnable core.
- Project: Build a Real-Time Chat Room with Ktor Build a multi-room chat with Ktor WebSockets. Design the message protocol, manage connections and rooms safely with coroutines, broadcast with SharedFlow, add history and test it. Includes a runnable core.
- Project: A Task API with Authentication and a Database Build a complete REST API in Ktor: register and log in with JWT, own tasks per user, validate input, handle errors, store data with Exposed, paginate and test. Includes runnable core logic.
- Practice: Ktor Exercises and Review Test your Ktor skills with graded exercises: routing, validation, auth, Exposed, WebSockets, testing and coroutines. Runnable stand-in challenges with solutions, a review checklist and next steps.