Estimate project
← All posts

Getting to Know Ktor from a Spring Boot Perspective. Part 2

We keep exploring Ktor through the eyes of a developer who knows Spring Boot well. This part walks you through handling HTTP requests and exceptions, HTTP clients, and testing, showing how Ktor's built-in features simplify each of these areas.

17 min read
Spring BootKotlinKtorKotlinServerSide

Here we carry on exploring Ktor from the point of view of a developer who already knows Spring Boot. Part one laid the foundations, covering Application Setup, Server Engines, Configuration, and Dependency Injection. This time, we move on to more advanced topics of building web applications with Ktor. In this part, I’ll take you through HTTP Request Handling & Exception Handling, HTTP Clients, and Testing, showing how Ktor’s built-in features simplify each of these areas.

Handling HTTP requests

Handling HTTP requests through exposed REST endpoints is among the most fundamental jobs of a web application. That’s why every web framework comes with mechanisms for processing requests, both when things go well and when errors occur.

Just as in other areas, Spring Boot and Ktor approach this differently, in line with their different philosophies. In this chapter, we’ll look at how each framework lets you define and structure routes, work with request parameters, and respond to exceptional situations.

Defining and organizing routes

Spring Boot

Spring Boot relies on annotation-based controllers, which you can group by the endpoints they expose. At startup, the framework finds and registers these controllers on its own thanks to component scanning.

@RestController
@RequestMapping("/api/users")
class UserController(private val userService: UserService) {

    @GetMapping("/{id}")
    fun getUserById(@PathVariable id: Long): User = userService.getUserById(id)

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    fun createUser(@RequestBody user: User): User = userService.createUser(user)

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun deleteUser(@PathVariable id: Long) = userService.deleteUser(id)
}

@RestController 
@RequestMapping("/api/orders") 
class OrderController(private val orderService: OrderService) {

    @GetMapping("/{id}")
    fun getOrderById(@PathVariable id: Long): User = orderService.getOrderByIt(id)
}

Ktor

Ktor’s routing system takes advantage of Kotlin’s powerful DSL capabilities and offers a fluent, hierarchical way of nesting routes so that their structure mirrors URL paths naturally. In contrast to annotation-based frameworks, Ktor promotes modularization with extension functions, so developers can put related routes into separate files.

// Application.kt
fun Application.configureRouting() {
    routing {
        userRoutes()
        orderRoutes()
    }
}

// UserRoutes.kt
fun Route.userRoutes() {
    route("/api") {
        route("/users") {

            get("/{id}") {
                val id = call.parameters["id"]?.toLongOrNull() 
                        ?: return@get call.respondText("Invalid ID", status = BadRequest)

                val user = userService.getUserById(id)
                if (user != null) {
                     call.respond(user)
                } else {
                    call.respond(HttpStatusCode.NotFound)
                }
           }

            post {
                val user = call.receive<User>()
                val createdUser = userService.createUser(user)
                call.respond(HttpStatusCode.Created, createdUser)
            }

            delete("/{id}") {
                val id = call.parameters["id"]?.toLongOrNull() 
                    ?: return@delete call.respondText("Invalid ID", status = BadRequest)

                userService.deleteUser(id)
                call.respond(HttpStatusCode.NoContent)
            }
        }
    }
}

// OrderRoutes.kt
fun Route.orderRoutes() {
    route("/api/orders") {

        get("/{id}") {
            val id = call.parameters["id"]?.toLongOrNull() 
                    ?: return@get call.respondText("Invalid ID", status = BadRequest)

            val user = orderService.getOrderById(id)
            if (user != null) {
                call.respond(user)
            } else {
                call.respond(HttpStatusCode.NotFound)
            }
        }
    }
}

The Application.configureRouting() function calls the routing() method, which installs the Routing plugin in the Ktor application. Inside the lambda body, two extension functions run and define the routes for Users and Orders.

A route definition starts with the path, specified with a DSL function such as route(“/api/users”). Within the corresponding lambda, endpoints are declared with functions named after HTTP methods (get, post, put, and so on).

To process incoming requests and return responses, you usually rely on the call property, which is an instance of RoutingCall. With it, you can:

  • Get the path variable, e.g., call.parameters[“id”]
  • Get the request parameter, e.g., call.request.queryParameters[“name”]
  • Get the request payload, e.g., call.receive()
  • Send back a response, e.g., call.respond(HttpStatusCode.NotFound)

Routing with type safety

Spring Boot

The controller-based model of Spring Boot gives you type safety for request and response bodies, but path variables and request parameters are mapped via strings, which are resolved at runtime and are therefore not type-safe.

@GetMapping("/users/{id}") // not type safe
fun getUser(@PathVariable id: Long): User {
    return userService.getUser(id)
}

Ktor

Ktor provides a more type-safe option through the Resources feature. It takes routing past string-based path definitions by modeling your API structure as a class hierarchy, in which every route is a strongly typed object with correctly typed parameters.

As a result, route parameters and paths are checked at compile time, which rules out typical runtime errors, and the href() function lets you generate URLs in a type-safe manner. Since routes are modeled as classes rather than strings, refactoring gets even safer and easier to handle. You just define the class hierarchy describing your API and use it in the routing definition.

// Define route structure as a class hierarchy
@Resource("/api/users")
class Users {

    @Resource("/{id}")
    class Id(val parent: Users, val id: Long) {

        @Resource("/orders")
        class Orders(val parent: Id)
    }

    @Resource("/search")
    class Search(val parent: Users, val sort: String? = "ASC")
}

// Use type-safe routing
routing {
    get<Users> {
        call.respond(userService.getAllUsers())
    }

    get<Users.Id> { route ->
        call.respond(userService.getUser(route.id))
    }

    get<Users.Id.Orders> { route ->
        call.respond(orderService.getOrdersForUser(route.parent.id))
    }

    get<Users.Search> { route ->
        call.respond(userService.searchUsers(route.sort))
    }
}

// Generate URLs type-safely
val usersUrl = application.href(Users()) // /api/users
val userUrl = application.href(Users.Id(Users(), 123)) // /api/users/123

To turn on Resources in Ktor, add the dependency below and install the Resources plugin:

dependencies {
    implementation("io.ktor:ktor-server-resources:$ktor_version")
}
fun Application.myAppModule() {
    install(Resources)
}

Handling exceptions

Spring Boot

Spring Boot offers a number of ways to handle exceptions: global handling with the @ControllerAdvice annotation, finer-grained handling at the controller level with @ExceptionHandler, implementing HandlerExceptionResolver, extending AbstractHandlerExceptionResolver, or using the ErrorController interface.

Here’s an example of the global approach based on @ControllerAdvice:

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException::class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    fun handleUserNotFound(e: UserNotFoundException): ErrorResponse {
        return ErrorResponse.from(e)
    }

    @ExceptionHandler(ValidationException::class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    fun handleValidation(e: ValidationException): ErrorResponse {
        return ErrorResponse.from(e)
    }

    @ExceptionHandler(Exception::class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    fun handleGeneric(e: Exception): ErrorResponse> {
        return ErrorResponse.from(e)
    }
}

Ktor

Ktor comes with a mechanism for handling exceptions thrown inside your application and returning suitable responses. As usual in Ktor, you have to turn this feature on with the install() function and add the corresponding dependency.

dependencies {
    implementation("io.ktor:ktor-server-status-pages:$ktor_version")
}
fun Application.configureErrorHandling() {
    install(StatusPages) {
        exception<UserNotFoundException> { call, cause ->
            call.respond(HttpStatusCode.NotFound, ErrorResponse.from(cause))
        }

        exception<ValidationException> { call, cause ->
            call.respond(HttpStatusCode.BadRequest, ErrorResponse.from(cause))
        }

        exception<Throwable> { call, cause ->
            call.respond(HttpStatusCode.InternalServerError, ErrorResponse.from("An unexpected error occurred"))
        }
    }
}

HTTP Clients

Hardly any modern web application, if any at all, just exposes an API without talking to other systems. This matters even more in a microservice architecture, where services frequently have to cooperate to carry out a business operation.

Such communication most often takes the form of a synchronous HTTP call, which means the application needs an HTTP client. Spring Boot and Ktor both offer powerful HTTP client libraries, yet they follow different philosophies and approaches. This chapter looks at how those approaches differ.

Handling requests and responses

Spring Boot

Spring Boot gives you several HTTP client options. For synchronous calls, there are two libraries: the older and well-known RestTemplate with its template method API, and the newer RestClient with a modern, fluent API. If you need asynchronous calls, there’s WebClient, a reactive, non-blocking option well suited to high-throughput systems.

Both clients offer rich functionality, such as manipulating requests and responses, handling errors, and automatic serialization/deserialization. Even so, WebClient is usually the preferred choice for new code thanks to its modern API design and tighter integration with Spring’s reactive ecosystem. I’ll use WebClient to compare the capabilities of Spring Boot’s HTTP client with those of Ktor.

Here’s how to call the /resources/{id} endpoint with the authorization header and the Accept header, and handle the response with WebClient.

fun getResource(id: Long): Mono<Resource> =
    webClient.get()
        .uri("/resources/{id}", id)
        .header(HttpHeaders.AUTHORIZATION, "Bearer token")
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToMono(Resource::class.java)

Ktor

Ktor’s HTTP client relies on Kotlin’s suspend functions and DSL to offer a compact syntax for sending requests: the HTTP method is a plain function call, and a request builder lambda holds the configuration. Calling the endpoint from the previous example with the authorization and Accept headers looks like this.

suspend fun getResource(id: Long): Resource =  
    client.get("https://api.example.com/resources/$id") {
        header(HttpHeaders.Authorization, "Bearer token")
        accept(ContentType.Application.Json)
    }.body()

Configuring the HTTP client

The examples above take for granted that the HTTP clients have already been configured. Before you can use them, though, the right configuration has to be in place. In this section, I’ll explain how the two frameworks differ in their approach to configuration.

Spring Boot

Thanks to auto-configuration, setting up WebClient in Spring Boot is easy: a WebClient builder bean is registered automatically, and you can inject it and customize it with very little code. You can build a fully customized WebClient bean by hand, but often it’s enough to take the pre-configured builder and add your own customizations.

Settings such as connection timeouts and response sizes can be configured in application properties instead of code. If you need to, however, you can also set up WebClient manually and define your own customized bean.

@Configuration
class WebClientConfig {

    @Bean
    fun webClient(): WebClient {
        return WebClient.builder()
            .baseUrl("https://api.example.com")
            .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
            .clientConnector(ReactorClientHttpConnector(HttpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .responseTimeout(Duration.ofMillis(5000))
                .doOnConnected { conn ->
                    conn.addHandlerLast(ReadTimeoutHandler(5, TimeUnit.SECONDS))
                    conn.addHandlerLast(WriteTimeoutHandler(5, TimeUnit.SECONDS))
                }
            ))
            .build()
    }
}

WebClient needs an underlying HTTP client library to work. Out of the box, it uses Reactor Netty. It can be swapped for Jetty’s reactive HTTP client if jetty-reactive-httpclient is on the classpath, or for Apache HttpComponents if httpclient5-reactive is available. Spring Boot detects your dependencies and configures the matching connector automatically.

Ktor

Ktor’s HTTP client provides a flexible configuration system built on plugins and a DSL, letting you add features such as logging, timeout handling, a retry mechanism, and JSON serialization with short, readable syntax. All features are off by default, so you need to turn each one on explicitly by installing its plugin and (usually) adding the appropriate dependencies.

The client works with several interchangeable engine implementations: CIO (Coroutine-based I/O), Ktor’s native engine tuned for Kotlin coroutines; Apache for legacy support; OkHttp for JVM and Android applications; Java’s HttpClient for standard JVM applications; and platform-specific engines for JavaScript and Native targets. This way, you can pick the implementation that best suits your runtime environment while keeping the API usage the same.

More about client engines is available here.

The configuration below sets Ktor’s client up to work with JSON. It logs all request and response data, and configures timeouts and request retries.

val client = HttpClient(CIO) {

    // Install content negotiation plugin with JSON support
    install(ContentNegotiation) {
        json()
   }

    // Logging configuration
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.ALL
    }

    // Timeouts configuration
    install(HttpTimeout) {
        requestTimeoutMillis = 5000
        connectTimeoutMillis = 5000
        socketTimeoutMillis = 5000
    }

    // Retries
    install(HttpRequestRetry) {
        retryOnServerErrors(maxRetries = 3)
        exponentialDelay()
    }

    // Engine-specific configuration
    engine {
        pipelining = true
        endpoint {
            connectTimeout = 5000
            socketTimeout = 5000
            requestTimeout = 5000
            keepAliveTime = 5000
        }
    }
}

Dependencies you need:

implementation("io.ktor:ktor-server-content-negotiation:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
implementation("io.ktor:ktor-client-core:$ktor_version")
implementation("io.ktor:ktor-client-cio:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")

Error handling

The first of the eight fallacies of distributed computing says that “the network is reliable.” As we know that’s false, we have to anticipate errors whenever an HTTP client makes network calls. Since this is such a common concern, most HTTP client libraries, Spring Boot’s and Ktor’s included, ship with built-in error handling mechanisms. Let’s see how they compare.

Spring Boot

In Spring Boot, WebClient handles errors declaratively through the onStatus function, which lets developers define custom error handling logic depending on HTTP status codes. The framework comes with an extensive exception hierarchy in which subtypes of WebClientResponseException map to different error categories (4xx, 5xx), and these can be caught and handled with standard exception handling techniques.

webClient.get()
    .uri("/resources/{id}", id)
    .retrieve()
    .onStatus({ it.is4xxClientError }) { response ->
        when (response.statusCode()) {
            HttpStatus.NOT_FOUND -> Mono.error(ResourceNotFoundException("Resource not found"))
            HttpStatus.UNAUTHORIZED -> Mono.error(UnauthorizedException("Unauthorized access"))
            else -> response.bodyToMono(String::class.java)
                .flatMap { Mono.error(ClientException("Client error: ${response.statusCode()}, body: $it")) }
        }
    }
    .onStatus({ it.is5xxServerError }) { response ->
        Mono.error(ServerException("Server error: ${response.statusCode()}"))
    }
    .bodyToMono(Resource::class.java)
    .onErrorResume(ResourceNotFoundException::class.java) { ex ->
        // Fallback logic
        Mono.just(Resource.notFound())
    }

Ktor

Ktor’s HTTP client gives you two ways of handling errors. You can deal with them programmatically by catching particular response validation exceptions, or you can rely on the dedicated HttpCallValidator plugin, which offers a global error handling mechanism.

For the first option, you need to set the “expectSuccess” flag to true, either in the HTTP client configuration or for an individual request. This makes Ktor’s client throw the appropriate exceptions on 4xx and 5xx status codes.

//  HTTP client configuration
val client = HttpClient(CIO) {
    expectSuccess = true
    // …
}

suspend fun getResource(id: Long): Result<Resource> {
    return try {
        val resource = client.get<Resource>("https://api.example.com/resources/$id")
        Result.success(resource)
    } catch (e: ClientRequestException) {
        // 4xx responses
        when (e.response.status.value) {
            404 -> Result.failure(ResourceNotFoundException("Resource not found"))
            401 -> Result.failure(UnauthorizedException("Unauthorized access"))
            else -> Result.failure(e)
        }
    } catch (e: ServerResponseException) {
        // 5xx responses
        Result.failure(ServerException("Server error: ${e.response.status.value}"))
    } catch (e: Exception) {
        // Connection, timeout, or other errors
        Result.failure(e)
    }
}

And here’s how to set up global handling with HttpCallValidator.

install(HttpCallValidator) {
    handleResponseExceptionWithRequest { exception, request ->
        when (exception) {
            is ClientRequestException -> {
                val response = exception.response
                if (response.status.value == 401) {
                    throw UserUnauthorizedException(exception)
                } else {
                    handleClientException(exception)
                }
            }
            is ServerResponseException -> {
                handleServerError(exception)
            }
            else -> throw exception
        }
    }
}

Testing

Testing matters not only for checking that your code fulfils the requirements, but also for making sure it keeps working correctly as it changes. The topic has many aspects, but to keep things simple, I’ll concentrate on the three kinds of tests developers most often use in their projects: unit, integration, and slice tests.

In this chapter, you’ll see how these tests are usually written in Spring Boot and how to get the same results in Ktor with the Kotest framework. As this article aims to give an overview of these web frameworks, it doesn’t go into the full details of Kotest.

Unit tests

Spring Boot

Unit tests check how individual classes or methods behave in isolation. They’re fast and help catch logic mistakes before dependencies and external systems get involved. Since unit tests work at the class level, the Spring Boot framework doesn’t offer any special support for them. Usually, we write unit tests with a testing library (JUnit, TestNG, Spock in Groovy, etc.) together with Mockito, which can stub the dependencies of the class under test. The example below is based on JUnit 5.

@ExtendWith(MockitoExtension::class)
class UserServiceTest {

    @Mock
    private lateinit var repo: UserRepository

    @InjectMocks
    private lateinit var systemUnderTest: UserService

    @Test
    fun `should return user when found`() {
        val user = User(1L, "Alice")
        whenever(repo.findById(1L)).thenReturn(Optional.of(user))

        val result = systemUnderTest.findById(1L)

        assertThat(result.name).isEqualTo("Alice")
        verify(repo).findById(1L)
    }

    @Test
    fun `should throw when not found`() {
        whenever(repo.findById(any())).thenReturn(Optional.empty())

        assertThatThrownBy { systemUnderTest.findById(42L) }
          .isInstanceOf(NotFoundException::class.java)
    }
}

Kotest / Koin

Just like Spring Boot, Ktor has no special features for unit testing. Depending on which dependency-injection framework you use, unit tests may need some extra boilerplate. With Koin (as described in earlier chapters), for instance, you have to start the Koin context and define a testing module that supplies your mocked dependencies.

In the example below, I’ve defined a test module with a mocked UserRepository, whose behavior can be set up separately for each test case. The system under test (UserService), on the other hand, is a real instance that gets the mocked repository via dependency injection. This lets you shape the repository’s behavior to fit the specific needs of every test.

class UserServiceTest : StringSpec(), KoinTest {
    private val testModule = module {
        single<UserRepository> { mockk(relaxed = true) }
        single { UserService(get()) }
    }

    private val repo: UserRepository by inject()
    private val systemUnderTest: UserService by inject()

    init {
        beforeSpec {
            startKoin { modules(testModule) }
        }
        afterSpec {
            stopKoin()
        }

        "should return user when found" {
            val user = User(1, "Alice")
            every { repo.getById(1) } returns user
            systemUnderTest.findById(1).name shouldBe "Alice"
            verify { repo.getById(1) }
        }

        "should throw exception when not found" {
            every { repo.getById(any()) } returns null
            shouldThrow<NotFoundException> { systemUnderTest.findById(42) }
        }
    }
}

Integration tests

Integration tests cover a bigger part of your application, usually starting the entire context (with a real HTTP server, database connections, migrations, serialization, etc.) to check that components cooperate properly. They tend to be slower than unit tests, but they’re extremely valuable for finding configuration errors, runtime mismatches, and integration points that unit tests alone can’t reveal.

Spring Boot

Spring Boot integration tests usually rely on the @SpringBootTest annotation, which starts the complete application context, including your controllers, services, repositories, and any embedded server or database configuration. Such tests confirm that your Spring beans are wired properly, that configuration properties take effect, and that real components (e.g., JPA repositories working against an embedded or test database) interact as intended. The example below checks the user creation process in a Spring Boot application.

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class UserIntegrationTest {

    @Autowired
    private lateinit var rest: TestRestTemplate

    @Test
    fun `create and fetch user`() {
        val newUser = mapOf("name" to "Alice")
        val create = rest.postForEntity("/users", newUser, UserDto::class.java)
        assertThat(create.statusCode).isEqualTo(HttpStatus.CREATED)

        val id = create.body!!.id
        val get = rest.getForEntity("/users/$id", UserDto::class.java)
        assertThat(get.body!!.name).isEqualTo("Alice")
    }
}

Ktor

Ktor integration tests usually use the built-in test engine (through testApplication { … }) to start your modules and plugins in an in-memory server and then exercise it with an HTTP client, exactly as a real client would. You can plug in test databases (e.g., H2 or TestContainers) and run your migrations, but every feature has to be installed and configured explicitly in your test setup.

Whereas Spring Boot starts the whole application context automatically, Ktor integration tests boot faster and give you precise control, because each feature is installed and configured explicitly. Spring Boot tests, in turn, prioritize convenience and wider coverage of your application’s auto-configured environment. The example below tests creating a user in our application with an H2 in-memory database.

class UserIntegrationTest : StringSpec({
    "create and fetch user" {
        testApplication {
            environment {
                config = MapApplicationConfig(
                    "ktor.deployment.port" to "0",
                    "database.url" to "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
                    "database.username" to "sa",
                    "database.password" to "XXX"
                )
            }
            application {
                myAppModule()
            }
            val client = createClient {
                install(io.ktor.client.plugins.contentnegotiation.ContentNegotiation) {
                    json()
                }
            }
            val createResp = client.post("/users") {
                contentType(ContentType.Application.Json)
                setBody(UserDto(name = "Alice"))
            }
            createResp.status shouldBe HttpStatusCode.Created
            val id = createResp.body<UserDto>().id
            // Fetch user
            val getResp = client.get("/users/$id")
            getResp.status shouldBe HttpStatusCode.OK
            getResp.body<UserDto>().name shouldBe "Alice"
        }
    }
})

Slice tests

Slice tests target one layer, or “slice”, of your application, for example the web, service, or data layer. In - web applications, they’re usually used to test controllers or routing without starting the whole application. Only the beans and configuration that the slice needs are loaded, and everything else is mocked. That’s why they’re faster than full integration tests while still checking real interactions inside the slice.

Spring Boot

Spring Boot slice tests use dedicated test annotations such as @WebMvcTest, @DataJpaTest, or @RestClientTest to load just the parts of the application context that belong to the given layer, mocking everything else. The code below tests UserController with the @WebMvcTest annotation, which starts the controller slice and relies on a mocked UserService to check that the controller behaves correctly.

@WebMvcTest(UserController::class)
class UserControllerTest {

    @Autowired
    private lateinit var mvc: MockMvc

    @MockBean
    private lateinit var service: UserService

    @Test
    fun `should return user`() {
        given(service.findById(1L)).willReturn(User(1L, "Alice"))

        mvc.perform(get("/users/1"))
           .andExpect(status().isOk)
           .andExpect(jsonPath("$.name").value("Alice"))
    }
}

Ktor

Ktor has no dedicated feature for slice tests. You can, however, use the testApplication DSL mentioned earlier to start only the particular modules or routes you want to check, installing only selected plugins (e.g., ContentNegotiation, Authentication) and plugging in Koin overrides or mocked dependencies for the rest.

This lets you exercise those slices directly and check serialization, validation, and routing logic in isolation from the real database or external services. The example below uses the testApplication DSL to install JSON content negotiation, define a Koin module with a mocked UserService, and define only the user-related routes, so that just the routing slice is tested.

class UserRoutesTest : StringSpec({
    "should return user" {
        val mockService = mockk<UserService>()
        every { mockService.findById(1) } returns User(1, "Alice")

        testApplication {
            install(ContentNegotiation) { json() }
            install(Koin) {
                modules(module { single { mockService } })
            }

            routing { userRoutes() }
            val response = client.get("/users/1")
            response.status shouldBe HttpStatusCode.OK
            response.body<UserDto>().name shouldBe "Alice"
        }
    }
})

Summary of Part 2

This part of the article set out to present the Ktor framework, pointing out its main features and relating them to familiar Spring Boot concepts to make learning easier. Here’s a recap of the topics we covered and compared:

HTTP Request Handling

  • Spring Boot: Controllers based on annotations
  • Ktor: Routing based on a DSL with extension functions, plus fully type-safe routing

Exception Handling

  • Spring Boot: Relies on @ControllerAdvice and @ExceptionHandler
  • Ktor: Relies on the StatusPages plugin with registered handlers

HTTP Clients

  • Spring Boot: Provides RestTemplate and WebClient with declarative error handling
  • Ktor: Relies on suspend functions, configuration through plugins, and programmatic error handling

Testing

  • Spring Boot: Relies on JUnit 5 (or other JVM frameworks) and Mockito for unit tests, @WebMvcTest + MockMvc for slice tests of controllers (or their equivalents for other slices), and @SpringBootTest + TestRestTemplate for full integration tests.
  • Ktor: Relies on Kotest and MockK (plus, e.g., Koin for DI) for unit tests, and on the testApplication { … } DSL for both slice and integration tests, with an in-process HTTP client and a configurable application environment – this gives you more control over what you test, at the cost of more ceremony.

Both parts of the article cover a lot of ground, but they don’t touch on everything you need when building a web application with Ktor. You’ll probably have to learn more to use Ktor successfully in your projects.