Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Boot, Apache Camel, and Swagger UI

DZone's Guide to

Spring Boot, Apache Camel, and Swagger UI

Learn how to integrate the popular Spring Boot framework and Swagger UI library using the open source and flexible integration tool, Camel.

· Integration Zone ·
Free Resource

How to Transform Your Business in the Digital Age: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.

Companies are using lots of systems which have to talk with each other. Therefore it's a good idea to use something to integrate these systems. Such an application integration can be done by an Enterprise Service Bus or even with an integration framework like Apache Camel. I highly recommend you use one of these and don't program it on your own by using lots of APIs. Please don't do this!

I'm a big fan of lightweight integration and flexibility so it's not surprising that Apache Camel is my tool of choice. Apache Camel can be used in standalone mode by using a jar containing the Camel routes or as part of a runtime like Spring Boot or WildFly/WildFly Swarm, for example. I decided to use Spring Boot as runtime because it is widely used and comes with a lot of useful things, very good documentation, and so on. In addition to that, I'm using Swagger UI to get a beautiful API documentation which makes consuming REST APIs much easier.

This blog post describes how to combine these technologies with each other. In case you just want to use the code, here's the link to my GitHub repository.

Create a Spring Boot and Apache Camel Project

First, we have to create a Spring Boot project containing the Apache Camel dependency first. This can easily be done by using the Spring Initializr which is available at https://start.spring.io/

You just change the Group and Artifact to the names you like and add Apache Camel as a Spring Boot Starters dependency. After that, you have to click on Generate Project and your project is up and running.

Integrate Swagger UI in Spring Boot

Now we can add the Swagger UI files to our Spring Boot project. This can be done by downloading the Swagger UI sources from GitHub

Note: I'm using Swagger UI 2.2.8 instead of the latest version because the Camel component doesn't support the new API specification of Swagger 3.X for now.

After that, we have to create a new folder at src/main/resources which have to be named: static, public or resources to serve our static Swagger UI content via Spring Boot. Now we simply have to add the dist folder of Swagger UI to this folder to make Swagger UI available in our project.

After that, Swagger UI is available at: http://localhost:8080/swagger/index.html

Add a Camel Route

In the next step, we have to add a simple Camel route to the Spring Boot project. To do this, we have to add a Camel servlet first.

package com.schulz.bennet.springbootswagger;

import org.apache.camel.component.servlet.CamelHttpTransportServlet;
import org.apache.camel.component.swagger.DefaultCamelSwaggerServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class SpringBootSwaggerApplication {

    private static final String CAMEL_URL_MAPPING = "/api/*";
    private static final String CAMEL_SERVLET_NAME = "CamelServlet";

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSwaggerApplication.class, args);
    }

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean registration =
                new ServletRegistrationBean(new CamelHttpTransportServlet(), CAMEL_URL_MAPPING);
        registration.setName(CAMEL_SERVLET_NAME);
        return registration;
    }
}

This snippet adds a servlet mapping which will be the prefix of all Camel routes we will add later. After that, all Camel routes will be available at localhost:8080/api/*. Now its time to add the route itself:

package com.schulz.bennet.springbootswagger;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.stereotype.Component;

@Component
public class PersonRoute extends RouteBuilder {

    @Override
    public void configure() {
        restConfiguration().component("servlet").bindingMode(RestBindingMode.xml);

        rest("/person").get().outType(Person.class)
                .to("direct:talk");
        from("direct:talk")
                .process(exchange -> {
                    Person p = new Person();
                    p.setFirstname("Bennet");
                    p.setLastname("Schulz");
                    exchange.getIn().setBody(p);
                });
    }
}

This route adds a person REST URI which can be used by HTTP GET only and returns a JSON response of my Person POJO class:

package com.schulz.bennet.springbootswagger;

public class Person {

    private String firstname;
    private String lastname;

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

After these steps, the Person respone is available at: http://localhost:8080/api/person

Combining Swagger and Camel Routes

After adding the REST API, it's time to combine Camel and Swagger UI with each other. This can be done by changing the URL in the Swaggerindex.html from the sample petstore to /api-doc/camel-1:

<!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
          url = "/api-doc/camel-1";
      }
      hljs.configure({
        highlightSizeThreshold: 5000
      });
      // Pre load translate...
      if(window.SwaggerTranslator) {
        window.SwaggerTranslator.translate();
      }

Now we have to add a servlet mapping for Swagger to use the Camel route URLs:

package com.schulz.bennet.springbootswagger;

import org.apache.camel.component.servlet.CamelHttpTransportServlet;
import org.apache.camel.component.swagger.DefaultCamelSwaggerServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
public class SpringBootSwaggerApplication {

    private static final String CAMEL_URL_MAPPING = "/api/*";
    private static final String CAMEL_SERVLET_NAME = "CamelServlet";

    public static void main(String[] args) {
        SpringApplication.run(SpringBootSwaggerApplication.class, args);
    }

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean registration =
                new ServletRegistrationBean(new CamelHttpTransportServlet(), CAMEL_URL_MAPPING);
        registration.setName(CAMEL_SERVLET_NAME);
        return registration;
    }

    @Bean
    public ServletRegistrationBean swaggerServlet() {
        ServletRegistrationBean swagger = new ServletRegistrationBean(new DefaultCamelSwaggerServlet(), "/api-doc/*");
        Map<String, String> params = new HashMap<>();
        params.put("base.path", "api");
        params.put("api.title", "my api title");
        params.put("api.description", "my api description");
        params.put("api.termsOfServiceUrl", "termsOfServiceUrl");
        params.put("api.license", "license");
        params.put("api.licenseUrl", "licenseUrl");
        swagger.setInitParameters(params);
        return swagger;
    }
}

After that, Swagger UI will use the Camel REST API instead of the sample petstore. It's important to change the base.path of the servlet to api because our REST APIs have /api/ as a prefix. These steps let Swagger UI show a beautiful documentation of our Camel REST APIs.

Have fun with it! 

Bye,
Bennet

Make your mark on the industry’s leading annual report. Fill out the State of API Integration 2019 Survey and receive $25 to the Cloud Elements store.

Topics:
integeration ,apache camel ,spring boot ,swagger

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}