Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

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.

Reading about a framework is not the same as using it. This page gives you graded exercises that cover the whole course. Some are real Ktor tasks: you write the code in your own Gradle project (see Project Setup with Gradle) and run it. Others are runnable challenges in plain Kotlin that practice the logic behind a Ktor feature; you can edit and run those right here. Try each exercise before reading the hint, and compare with the solution only at the end.

About the runnable parts. The site cannot run Ktor itself, so the challenges below use plain Kotlin stand-ins for the underlying ideas (route matching, rate limiting, validation, coroutines). The real Ktor exercises have no runnable version here; you verify them with your own server and testApplication tests.

Level 1: Routing and requests

Exercise 1.1 (real Ktor). Create a server with GET /hello (plain text), GET /hello/{name} (greets the name; respond 400 if the name is longer than 30 characters) and GET /sum?a=1&b=2 (JSON {"sum": 3}; 400 with a message when a parameter is missing or not a number). Write one testApplication test per route, including the error cases. Review: Routing Basics, Path and Query Parameters.

Exercise 1.2 (runnable). A router chooses the most specific route: a literal segment beats a , which beats a wildcard *. Implement match so that the output in main appears as shown in the comments. Edit and run it.

Kotlin Challenge: route matching by specificity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Stretch: add a method to each route and return 405 Method Not Allowed when the path matches but the method does not.

Level 2: Plugins, JSON and errors

Exercise 2.1 (real Ktor). Install ContentNegotiation with kotlinx.serialization and build POST /books accepting {"title": "...", "year": 2020}. Use RequestValidation to reject an empty title or a year outside 1450 to the current year, and StatusPages so that every error (validation, malformed JSON, unknown route, unexpected exception) returns {"error": "...", "status": 400}. Make sure a stack trace never reaches the client. Review: Content Negotiation and JSON, Request Validation, Status Pages.

Exercise 2.2 (runnable). Write a validator that collects all problems instead of stopping at the first, which gives a much better API experience. Edit the rules and run it.

Kotlin Challenge: collect every validation error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Level 3: Authentication

Exercise 3.1 (real Ktor). Add JWT authentication to your server: POST /login accepts a hard-coded user and returns a token that expires in 15 minutes; GET /me requires the token and returns the user name. Then add roles (admin, user): DELETE /books/{id} needs admin. Write tests for: no token (401), expired token (401), valid user token on an admin route (403), admin token (204). Review: Authentication Basics, Bearer Tokens and JWT, OAuth and Authorization.

Exercise 3.2 (runnable). Implement a role check and use the right status codes: 401 means "I do not know who you are", 403 means "I know who you are, and you may not".

Kotlin Challenge: 401 versus 403

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Level 4: Databases

Exercise 4.1 (real Ktor). Replace your in-memory book store with Exposed and an H2 or PostgreSQL database. Define Books and Authors tables with a foreign key, write a repository with create, find, list(page, size) and delete, and do all database work through a dbQuery helper that uses Dispatchers.IO. Add a migration with Flyway instead of SchemaUtils.create. Prove that a failed insert inside a transaction leaves no partial data. Review: Exposed Overview, Querying with the DSL, DAO and Relations, Pooling and Migrations.

Exercise 4.2 (runnable). Cursor ("keyset") pagination: return the items after a given id, plus the cursor for the next page. Complete and run it.

Kotlin Challenge: keyset pagination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Why fetch size + 1 rows? It tells you whether another page exists without a second COUNT query.

Level 5: Real-time

Exercise 5.1 (real Ktor). Build GET /events as Server-Sent Events that emits the current time every second, and webSocket("/echo") that returns every text frame in upper case and closes politely on the message bye. Test both with testApplication. Then add a webSocket("/room") where messages are broadcast to all connected clients. Review: WebSockets in Ktor, Server-Sent Events, Channels and Broadcasting.

Exercise 5.2 (runnable). Use a coroutine to run a "ticker" that stops when its consumer cancels, and make sure cleanup code runs.

Kotlin Challenge: a flow that cleans up on cancel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Level 6: Testing and operations

Exercise 6.1 (real Ktor). Reach 80 percent route coverage on your book API: every route has a success test and at least one failure test. Use a fake repository in unit-style tests and the real database in one integration test. Add a test that proves a 500 error does not leak internals. Review: Testing Ktor Applications, Testing with Fakes and Databases.

Exercise 6.2 (real Ktor). Make it deployable: typed settings with validation (Configuration), a multi-stage Dockerfile (Docker), liveness and readiness endpoints, rate limiting on login and graceful shutdown (Production Readiness).

Exercise 6.3 (runnable). Implement a circuit breaker: after three failures in a row it opens and fails fast; after a cool-down it lets one trial call through. This protects your server when a downstream service is down (see The Ktor HTTP Client).

Kotlin Challenge: a circuit breaker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Capstone ideas

Pick one and build it end to end, using every chapter:

  1. Bookmarks service. Users, tags (many-to-many), full-text search with LIKE, import and export as JSON, and an SSE feed of new bookmarks.
  2. Polls and live results. Create polls, vote once per user, results pushed over WebSockets, rate-limited voting, admin role to close polls.
  3. File sharing. Upload with size limits, store metadata in Exposed, signed download links that expire, virus-scan hook as a background coroutine job.
  4. Status dashboard. An HTTP client that pings a list of URLs concurrently with timeouts, stores history, exposes /status and pushes changes over WebSockets.

Review checklist

Before you call a Ktor service finished, check:

  • Every route has a success and a failure test, and errors share one JSON shape.
  • Inputs are validated; list endpoints are paginated and capped.
  • Every data query is scoped to the authenticated user where it should be.
  • Blocking work uses Dispatchers.IO; outbound calls have timeouts and sensible retries.
  • Configuration is typed, validated and comes from the environment; no secrets in Git or logs.
  • The image is small and runs as non-root; health checks, metrics and graceful shutdown exist.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A request has a valid token but the user lacks the required role. Which status fits?

    The caller is identified (authenticated) but not allowed (not authorized).
  2. 2. Why fetch size + 1 rows in keyset pagination?

    An extra row proves more data exists and the last returned id becomes the cursor.
  3. 3. What does a circuit breaker do after repeated downstream failures?

    Failing fast protects your threads and gives the downstream service time to recover.
  4. 4. Which validation style gives clients the best experience?

    Collecting all errors lets the client fix them in one round trip.

Summary

  • Practice by building: do the real Ktor exercises in your own project and verify them with tests.
  • Use the runnable challenges to sharpen logic: route specificity, validation, 401 vs 403, pagination, cancellation, circuit breakers.
  • Finish with a capstone project and the review checklist.
  • Keep going with the Kotlin tutorial for the language and the Docker tutorial for deployment.

Next: Back to the Ktor course