DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Frameworks
  4. Non-Blocking REST APIs With Kotlin, Spring 5, Swagger, and Project Reactor

Non-Blocking REST APIs With Kotlin, Spring 5, Swagger, and Project Reactor

In this article, I will describe how to bootstrap a new Spring 5 project that integrates Kotlin, Spring Webflux functional, Project Reactor, Swagger, Gradle, and JUnit.

Carmine DiMascio user avatar by
Carmine DiMascio
CORE ·
Jan. 23, 18 · Tutorial
Like (15)
Save
Tweet
Share
31.19K Views

Join the DZone community and get the full member experience.

Join For Free

Early last year, Spring announced official support for Kotlin in Spring Framework 5. The news was welcome and exciting, particularly with respect to technologies like Spring Webflux, Project Reactor, and Spring functional, areas where Kotlin very much shines.

In this article, I will describe how to bootstrap a new Spring 5 project that integrates Kotlin, Spring Webflux functional, Project Reactor, Swagger, Gradle, and JUnit using kotlin-swagger-spring-functional-template. The template includes two sample REST endpoints and provides interactive API documentation and automatic request validation. 

You can view the complete template's source code on GitHub or try the live demo on IBM Cloud.

Before we get started, let’s look at the technologies behind the template project.

  • Kotlin — Statically typed programming language for modern multiplatform applications.
  • Spring 5 Webflux — The module contains support for reactive HTTP and WebSocket clients as well as for reactive server web applications including REST, HTML browser, and WebSocket style interactions.
  • Project Reactor —Reactor is a fourth-generation Reactive library for building non-blocking applications on the JVM based on the Reactive Streams Specification.
  • Swagger — Swagger is the world’s largest framework of API developer tools for the OpenAPI Specification (OAS), enabling development across the entire API lifecycle, from design and documentation, to test and deployment.
  • Swagger UI — Visualize and interact with the API’s resources.
  • OpenApi Spring Webflux Validator — A friendly Kotlin library used to validate Spring Functional API endpoints against a Swagger 2.0 specification. It leverages the Atlassian request validator.
  • JUnit 5 —JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.
  • JUnit Jupiter — JUnit Jupiter is the combination of the new programming model and extension model for writing tests and extensions in JUnit 5.
  • Gradle — Gradle helps teams build, automate, and deliver better software, faster.

Okay, let’s get started. Here’s how to use the template:

Clone the GitHub project:

git clone https://github.com/cdimascio/kotlin-swagger-spring-functional-template

Build it:

./gradlew build

Execute the tests:

./gradlew test

Run it (locally):

./gradlew run

Try it:

Navigate to http://localhost:8080/

As you can see, getting started with the template is fairly straightforward. Similarly, the template keeps validation simple. The following demonstrates the code required to validate a POST operation's request body:

UserHandler.kt

fun create(req: ServerRequest) = validate
    .request(req)
    .withBody(User::class.java) { user ->
        ok().body(Mono.just(user))
     }

And, with the Spring 5 Kotlin DSL, implementing routing logic is a breeze.

Router.kt

"/api".nest {
 accept(APPLICATION_JSON).nest {
    POST("/users", userHandler::create)
    }
}

Notice that neither the router nor the handler code contains any validation logic. This is because validation is handled declaratively. The template project reads the Open API (Swagger) specification JSON and enforces it.

Below is a snippet from the specification JSON. Notice that it defines firstname  and lastname as required properties on the User POST body. 

 "definitions": {
    "User": {
      "required": [
        "firstname",
        "lastname"
      ],
      "properties": {
        "firstname": {
          "type": "string"
        },
        "lastname": {
          "type": "string"
        }
      }
    }
 }

This validation logic is then enforced automatically by swagger-spring-functional (also included in the template project). swagger-spring-functional is configured as follows:

val validate = Validate.configure("static/api.json") { status, messages ->
    // optionally specify a custom error object
    Error(status.value(), messages)
}

Finally, the template project uses Swagger UI to provide beautiful, interactive API documentation. The doc is always kept in sync with the validation logic as both reference the same specification JSON.

To conclude, kotlin-swagger-spring-functional-template makes it easy to get started with Kotlin, Spring 5, and Swagger. It handles the basics for you and provides automatic request validation, interactive API docs, and more. It bootstraps your project, so you don't have to, letting you focus on what matters most - your code.

Spring Framework REST Web Protocols Kotlin (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • Understanding gRPC Concepts, Use Cases, and Best Practices
  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • How To Use Terraform to Provision an AWS EC2 Instance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: