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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Aggregating REST APIs Calls Using Apache Camel

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • Designing for Sustainability: The Rise of Green Software
  • Designing AI Multi-Agent Systems in Java
  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  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.

By 
Carmine DiMascio user avatar
Carmine DiMascio
·
Jan. 23, 18 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
32.8K 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.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • Aggregating REST APIs Calls Using Apache Camel

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!