Skip to content

project rulesBackend and APIskotlin

Kotlin Ktor Rules

Project rules for Ktor servers: routing extension functions, kotlinx serialization, auth plugins, structured coroutines and testApplication tests.

npx workspacetemplates add kotlin-ktor-rules --tool claude-code

Writes 1 file to your project root

CLAUDE.mdadd to your file24 lines · 1.4 KBFile
# Project rules: Ktor server

## Structure
- `Application.module()` only installs plugins and calls feature functions such as `Route.orderRoutes(service)`. One file per feature with routes, service and repository.
- Wire dependencies by constructor, using Koin or plain functions. No global singletons.

## Plugins
- Install `ContentNegotiation` with kotlinx.serialization and `@Serializable` request and response classes. Do not reflect over domain objects.
- Use `StatusPages` to map exceptions to a single error body and status. Use `CallLogging` with a call id.
- Authenticate with the `Authentication` plugin (JWT or session); wrap protected routes in `authenticate("name") { ... }`. Keep keys and secrets in environment config.

## Coroutines
- Handlers are `suspend`. Run blocking JDBC or file work in `withContext(Dispatchers.IO)`, or use a driver that suspends.
- Never use `GlobalScope` or `runBlocking` in server code. Launch background work from an application-scoped `CoroutineScope`.
- Respect cancellation; do not swallow `CancellationException`.

## Data and config
- Read settings from `application.conf` or YAML with environment overrides. Use Exposed or jOOQ transactions with explicit boundaries.

## Tests
- Use `testApplication { }` with the real module and a test config; call endpoints through `client`. Test auth failures as well as happy paths.

## Before finishing
Run `./gradlew ktlintCheck test build`.

What it does

Ktor gives you a toolkit, not a layout, so two agents will build two different servers. These rules choose a layout built from small routing extensions and installable plugins.

They also keep coroutine use safe on the server, where a blocking call or leaked job quietly reduces throughput for every request.

Example

you › Add a protected endpoint listing the caller's invoices

agent › The agent adds a routing extension under authenticate, reads the principal, queries on the IO dispatcher, returns a serializable list, and tests both 200 and 401 with testApplication.

Questions

Does it require Koin?
No. Any constructor-based wiring works. Koin is named only as a common option.
Why avoid runBlocking?
It parks a server thread until the work finishes, which cancels the benefit of coroutines and can stall unrelated requests.
  • ASP.NET Core Web API Rules

    Project rulesdotnet

    Free
  • Django Rules

    Project rulespython

    Free
  • Flask Rules

    Project rulespython

    Free
  • Go Service Rules

    Project rulesgo

    Free