Skip to content
Skillpedia
General coding280k Β· #195

kotlin-ktor-patterns

What it does

This code helps build web servers using the Kotlin language. It organizes the different parts of the server, such as routes (the paths users access), how data is sent and received, and how to protect access.

When to use it

  • βœ“When you are starting to build a website or web application with Kotlin.
  • βœ“When defining which addresses (URLs) your server will respond to.
  • βœ“When you need to configure who can access certain parts of your server.

Skill link

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/kotlin-ktor-patterns/SKILL.md

Copy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.

How to use

The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.

Ready-to-paste message

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/kotlin-ktor-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

Example of what to ask your AI

β€œHow can I set up my Ktor server to accept data in JSON format?”

5 new skills a week. 1 minute to read.

How it works

It uses a set of 'recipes' (patterns) to organize the server code. These recipes show how to set up routes, handle security, and ensure data is formatted correctly.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

Ktor Server Patterns

Comprehensive Ktor patterns for building robust, maintainable HTTP servers with Kotlin coroutines.

When to Activate

  • Building Ktor HTTP servers
  • Configuring Ktor plugins (Auth, CORS, ContentNegotiation, StatusPages)
  • Implementing REST APIs with Ktor
  • Setting up dependency injection with Koin
  • Writing Ktor integration tests with testApplication
  • Working with WebSockets in Ktor

Application Structure

Standard Ktor Project Layout

src/main/kotlin/
β”œβ”€β”€ com/example/
β”‚   β”œβ”€β”€ Application.kt           # Entry point, module configuration
β”‚   β”œβ”€β”€ plugins/
β”‚   β”‚   β”œβ”€β”€ Routing.kt           # Route definitions
β”‚   β”‚   β”œβ”€β”€ Serialization.kt     # Content negotiation setup
β”‚   β”‚   β”œβ”€β”€ Authentication.kt    # Auth configuration
β”‚   β”‚   β”œβ”€β”€ StatusPages.kt       # Error handling
β”‚   β”‚   └── CORS.kt              # CORS configuration
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ UserRoutes.kt        # /users endpoints
β”‚   β”‚   β”œβ”€β”€ AuthRoutes.kt        # /auth endpoints
β”‚   β”‚   └── HealthRoutes.kt      # /health endpoints
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ User.kt              # Domain models
β”‚   β”‚   └── ApiResponse.kt       # Response envelopes
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ UserService.kt       # Business logic
β”‚   β”‚   └── AuthService.kt       # Auth logic
β”‚   β”œβ”€β”€ repositories/
β”‚   β”‚   β”œβ”€β”€ UserRepository.kt    # Data access interface
β”‚   β”‚   └── ExposedUserRepository.kt
β”‚   └── di/
β”‚       └── AppModule.kt         # Koin modules
src/test/kotlin/
β”œβ”€β”€ com/example/
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   └── UserRoutesTest.kt
β”‚   └── services/
β”‚       └── UserServiceTest.kt

Application Entry Point

// Application.kt
fun main() {
    embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}

fun Application.module() {
    configureSerialization()
    configureAuthentication()
    configureStatusPages()
    configureCORS()
    configureDI()
    configureRouting()
}

Routing DSL

Basic Routes

// plugins/Routing.kt
fun Application.configureRouting() {
    routing {
        userRoutes()
        authRoutes()
        healthRoutes()
    }
}

// routes/UserRoutes.kt
fun Route.userRoutes() {
    val userService by inject<UserService>()

    route("/users") {
        get {
            val users = userService.getAll()
            call.respond(users)
        }

        get("/{id}") {
            val id = call.parameters["id"]
                ?: return@get call.respond(HttpStatusCode.BadRequest, "Missing id")
            val user = userService.getById(id)
                ?: return@get call.respond(HttpStatusCode.NotFound)
            call.respond(user)
        }

        post {
            val request = call.receive<CreateUserRequest>()
            val user = userService.create(request)
            call.respond(HttpStatusCode.Created, user)
        }

        put("/{id}") {
            val id = call.parameters["id"]
                ?: return@put call.respond(HttpStatusCode.BadRequest, "Missing id")
            val request = call.receive<UpdateUserRequest>()
            val user = userService.update(id, request)
                ?: return@put call.respond(HttpStatusCode.NotFound)
            call.respond(user)
        }

        delete("/{id}") {
            val id = call.parameters["id"]
                ?: return@delete call.respond(HttpStatusCode.BadRequest, "Missing id")
            val deleted = userService.delete(id)
            if (deleted) call.respond(HttpStatusCode.NoContent)
            else call.respond(HttpStatusCode.NotFound)
        }
    }
}

Route Organization with Authenticated Routes

fun Route.userRoutes() {
    route("/users") {
        // Public routes
        get { /* list users */ }
        get("/{id}") { /* get user */ }

        // Protected routes
        authenticate("jwt") {
            post { /* create user - requires auth */ }
            put("/{id}") { /* update user - requires auth */ }
            delete("/{id}") { /* delete user - requires auth */ }
        }
    }
}

Content Negotiation & Serialization

kotlinx.serialization Setup

// plugins/Serialization.kt
fun Application.configureSerialization() {
    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
            isLenient = false
            ignoreUnknownKeys = true
            encodeDefaults = true
            explicitNulls = false
        })
    }
}

Serializable Models

@Serializable

…
FAQ

What is a 'route'?

A route is like a specific address on your web server. For example, '/users' might be a route to view a list of users.

What does 'authentication' mean?

Authentication is the process of verifying if a user is who they claim to be, usually by asking for a username and password or a token.

What is 'dependency injection' (DI)?

It's a way of organizing code where parts of the program receive the other parts they need, instead of creating them themselves. This makes the code easier to manage.

Details

Original description by the author

Ktor server patterns including routing DSL, plugins, authentication, Koin DI, kotlinx.serialization, WebSockets, and testApplication testing. Use when building a Ktor server β€” routing, plugins, auth, DI, serialization, or tests.

repo: affaan-m/ECC

Popularity

GitHub stars
280k
Ranking position
#195
License
MIT
Updated
10/15/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills