Over a million developers have joined DZone.

Spring Webflux: Kotlin DSL [Snippets]

DZone's Guide to

Spring Webflux: Kotlin DSL [Snippets]

If you haven't kept up with Spring Webflux, you can now define functional application endpoints with a Kotlin-based DSL.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Spring Webflux recently introduced a feature to define functional application endpoints using a very intuitive Kotlin-based DSL.

This post will be to simply show a contrasting API defined using a Java-based fluent API and a Kotlin based DSL.

A functional way to define a CRUD-based Spring Webflux endpoint in Java would look like this:

RouterFunction<?> apis() {
    return nest(path("/hotels"), nest(accept(MediaType.APPLICATION_JSON),
                    GET("/"), messageHandler::getMessages)
                    .andRoute(POST("/"), messageHandler::addMessage)
                    .andRoute(GET("/{id}"), messageHandler::getMessage)
                    .andRoute(PUT("/{id}"), messageHandler::updateMessage)
                    .andRoute(DELETE("/{id}"), messageHandler::deleteMessage)

The details of the endpoint are very clear and are defined in a fluent manner with just a few keywords — route, nest, and the HTTP verbs.

These endpoints can be expressed using a Kotlin-based DSL (and some clever use of Kotlin extension functions) the following way:

fun apis() = router {
    (accept(APPLICATION_JSON) and "/messages").nest {
        GET("/", messageHandler::getMessages)
        POST("/", messageHandler::addMessage)
        GET("/{id}", messageHandler::getMessage)
        PUT("/{id}", messageHandler::updateMessage)
        DELETE("/{id}", messageHandler::deleteMessage)

I feel that this reads a little better than the Java-based DSL. If the API is more complicated, as demonstrated in the excellent samples by Sébastien Deleuze with multiple levels of nesting, the Kotlin-based DSL really starts to shine.

In the next post, I will delve into how this support has been implemented.

This sample is available in my GitHub repo here.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

java ,kotlin ,dsl ,spring webflux

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}