A multiplatform asynchronous framework for creating microservices, web applications, and HTTP clients written in Kotlin from the ground up
—
Type-safe routing DSL for defining HTTP endpoints and handling requests with Ktor server.
Install and configure the routing system in your Ktor application.
/**
* Install routing in the application
* @param configuration Routing configuration block
* @return Routing instance
*/
fun Application.routing(configuration: Routing.() -> Unit): Routing
/**
* Install routing plugin in the application
*/
fun Application.install(plugin: Routing): RoutingUsage Examples:
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.response.*
fun Application.configureRouting() {
routing {
get("/") {
call.respondText("Hello World!")
}
get("/users") {
call.respondText("User list")
}
}
}Core routing interface providing the foundation for all routing operations.
/**
* Core route interface
*/
interface Route {
/**
* Parent route or null if this is the root
*/
val parent: Route?
/**
* Route selector for matching requests
*/
val selector: RouteSelector
/**
* Development mode flag
*/
val developmentMode: Boolean
/**
* Application environment
*/
val environment: ApplicationEnvironment
/**
* Create a child route with the given selector
*/
fun createChild(selector: RouteSelector): Route
/**
* Select routes matching the given context
*/
fun select(context: RoutingResolveContext): RoutingResolveResult
}
/**
* Root routing interface
*/
interface Routing : Route {
/**
* All registered routes
*/
val allRoutes: List<Route>
}Route definitions for standard HTTP methods.
/**
* Handle GET requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.get(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
/**
* Handle POST requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.post(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
/**
* Handle PUT requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.put(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
/**
* Handle DELETE requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.delete(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
/**
* Handle HEAD requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.head(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
/**
* Handle OPTIONS requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.options(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): Route
/**
* Handle PATCH requests
* @param path URL path pattern
* @param body Request handler
* @return Created route
*/
fun Route.patch(
path: String = "",
body: suspend PipelineContext<Unit, ApplicationCall>.() -> Unit
): RouteUsage Examples:
routing {
// Basic routes
get("/") { call.respondText("Home page") }
post("/users") { call.respondText("Create user") }
put("/users/{id}") { call.respondText("Update user ${call.parameters["id"]}") }
delete("/users/{id}") { call.respondText("Delete user ${call.parameters["id"]}") }
// Path parameters
get("/users/{id}") {
val userId = call.parameters["id"]
call.respondText("User: $userId")
}
// Optional parameters
get("/posts/{id?}") {
val postId = call.parameters["id"]
if (postId != null) {
call.respondText("Post: $postId")
} else {
call.respondText("All posts")
}
}
}Organize routes into logical groups with shared configuration.
/**
* Create a route group with common path prefix
* @param path Common path prefix
* @param build Route configuration block
* @return Created route
*/
fun Route.route(
path: String,
build: Route.() -> Unit
): Route
/**
* Create a route group with HTTP method selector
* @param method HTTP method to match
* @param build Route configuration block
* @return Created route
*/
fun Route.method(
method: HttpMethod,
build: Route.() -> Unit
): Route
/**
* Create a route group with host selector
* @param host Host pattern to match
* @param build Route configuration block
* @return Created route
*/
fun Route.host(
host: String,
build: Route.() -> Unit
): Route
/**
* Create a route group with port selector
* @param port Port number to match
* @param build Route configuration block
* @return Created route
*/
fun Route.port(
port: Int,
build: Route.() -> Unit
): RouteUsage Examples:
routing {
// Path-based grouping
route("/api") {
route("/v1") {
get("/users") { call.respondText("V1 Users") }
get("/posts") { call.respondText("V1 Posts") }
}
route("/v2") {
get("/users") { call.respondText("V2 Users") }
get("/posts") { call.respondText("V2 Posts") }
}
}
// Host-based routing
host("api.example.com") {
get("/") { call.respondText("API Server") }
}
host("admin.example.com") {
get("/") { call.respondText("Admin Panel") }
}
// Port-based routing
port(8080) {
get("/") { call.respondText("Public API") }
usrs
port(8081) {
get("/") { call.respondText("Admin API") }
}
}Flexible route matching system for complex routing scenarios.
/**
* Base interface for route selectors
*/
sealed class RouteSelector {
/**
* Evaluate if this selector matches the given context
*/
abstract fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation
}
/**
* Path segment selector for literal path matching
*/
data class PathSegmentConstantRouteSelector(val value: String) : RouteSelector()
/**
* Path parameter selector for capturing path variables
*/
data class PathSegmentParameterRouteSelector(
val name: String,
val prefix: String = "",
val suffix: String = ""
) : RouteSelector()
/**
* Wildcard selector for capturing remaining path segments
*/
data class PathSegmentWildcardRouteSelector(val name: String) : RouteSelector()
/**
* Optional path segment selector
*/
data class PathSegmentOptionalParameterRouteSelector(val name: String) : RouteSelector()
/**
* HTTP method selector
*/
data class HttpMethodRouteSelector(val method: HttpMethod) : RouteSelector()
/**
* Accept header selector for content negotiation
*/
data class HttpAcceptRouteSelector(val contentType: ContentType) : RouteSelector()Route matching and resolution system.
/**
* Context for route resolution
*/
class RoutingResolveContext(
val routing: Route,
val call: ApplicationCall,
val parameters: ParametersBuilder = ParametersBuilder()
) {
val segments: List<String>
val headers: Headers
val method: HttpMethod
}
/**
* Result of route resolution
*/
sealed class RoutingResolveResult {
/**
* Successful route resolution
*/
data class Success(val route: Route, val parameters: Parameters) : RoutingResolveResult()
/**
* Failed route resolution
*/
object Failure : RoutingResolveResult()
}
/**
* Route evaluation result
*/
sealed class RouteSelectorEvaluation {
/**
* Successful evaluation
*/
data class Success(val segmentIncrement: Int) : RouteSelectorEvaluation()
/**
* Failed evaluation
*/
object Failed : RouteSelectorEvaluation()
/**
* Evaluation with quality factor
*/
data class SuccessWithQuality(val segmentIncrement: Int, val quality: Double) : RouteSelectorEvaluation()
}Integration with authentication system for protected routes.
/**
* Create authenticated routes that require valid authentication
* @param configurations Authentication configurations to require
* @param optional Make authentication optional
* @param build Route configuration block
* @return Created route
*/
fun Route.authenticate(
vararg configurations: String? = arrayOf<String?>(null),
optional: Boolean = false,
build: Route.() -> Unit
): RouteUsage Examples:
routing {
// Public routes
get("/") { call.respondText("Public page") }
post("/login") { /* handle login */ }
// Authenticated routes
authenticate {
get("/profile") { call.respondText("User profile") }
post("/logout") { /* handle logout */ }
// Admin-only routes
authenticate("admin") {
get("/admin") { call.respondText("Admin panel") }
delete("/users/{id}") { /* delete user */ }
}
}
// Optional authentication
authenticate(optional = true) {
get("/posts") {
val user = call.principal<UserPrincipal>()
if (user != null) {
call.respondText("Posts for ${user.name}")
} else {
call.respondText("Public posts")
}
}
}
}Install with Tessl CLI
npx tessl i tessl/maven-io-ktor--ktor