Over a million developers have joined DZone.

RESTful APIs With Camel and WildFly Swarm

Learn how to integrate Camel and the REST DSL inside a WildFly Swarm Microservice.

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

We’ve seen how to configure a very simple Camel route that responds to web requests. It is quite possible to build a RESTful style API using routes that respond to requests on the Camel servlet, but Camel provides a better way to generate these kinds of interfaces. By adding support for the Camel REST DSL we can build up a RESTful API by chaining together fluent route methods that describe the endpoint.

In addition to the new DSL, Camel also provides integration with Swagger which allows us to generate REST API documentation from the details that we define as part of the REST DSL. Swagger is a popular documentation tool, and transparently integrating the generation of this documentation into our RESTful API definition is a huge time saver for developers.

Adding the REST DSL and the Swagger library to our application requires adding the following dependencies:

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }

    dependencies {
        classpath "org.wildfly.swarm:wildfly-swarm-plugin:1.0.0.Beta7"
    }
}

group 'com.matthewcasperson'
version '1.0-SNAPSHOT'

apply plugin: 'war'
apply plugin: 'wildfly-swarm'

sourceCompatibility = 1.8

def swarmVersion = '1.0.0.Beta4'
def camelVersion = '2.17.0'
def camelRestVersion = '1.6.4'

repositories {
    mavenCentral()
    mavenLocal()
    maven {
        url 'http://repository.jboss.org/nexus/content/groups/public-jboss'
    }
    maven {
        url 'https://maven.repository.redhat.com/nexus/content/repositories/public'
    }
}

/*
    Fix this error:
    Could not determine artifacts for org.springframework:spring:3.0.0.M3
 */
configurations {
    all*.exclude group: 'org.springframework', module: 'spring'
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'

    compile 'com.sun.xml.bind:jaxb-core:2.2.11'
    compile 'com.sun.xml.bind:jaxb-impl:2.2.11'

    compile 'org.wildfly.swarm:bootstrap:' + swarmVersion
    compile 'org.wildfly.swarm:undertow:' + swarmVersion
    compile 'org.wildfly.swarm:weld:' + swarmVersion

    compile 'org.apache.camel:camel-core:' + camelVersion
    compile 'org.apache.camel:camel-servletlistener:' + camelVersion
    compile 'org.apache.camel:camel-servlet:' + camelVersion
    compile 'org.apache.camel:camel-cdi:' + camelVersion
    compile 'org.apache.camel:camel-spring:' + camelVersion
    compile 'org.apache.camel:camel-swagger-java:' + camelVersion

    compile 'org.apache.camel:camel-rest:' + camelRestVersion
}

// For heroku
task stage {
    dependsOn build
}


Before we can make use of the REST DSL, we need to configure it. There are three important things we need to do:

  1. Tell the REST DSL what component it will be receiving requests from. We will make use of the existing servlet component.
  2. Enable and configure the Swagger integration.
  3. Enable CORS for the Swagger endpoint.
package com.matthewcasperson.swarmdemo;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;

/**
 * Configure the REST DSL
 */
public class RestConfiguration extends RouteBuilder {

    @Override
    public void configure() {
        /*
            Configure we want to use servlet as the component for the rest DSL
            and we enable json binding mode
         */
        restConfiguration()
                /*
                    integrate the rest dsl to the servlet component
                 */
                .component("servlet")
                /*
                    default to json
                 */
                .bindingMode(RestBindingMode.json)
                /*
                    and output using pretty print
                 */
                .dataFormatProperty("prettyPrint", "true")
                /*
                    add swagger api-doc out of the box
                  */
                .apiContextPath("/api-docs")
                /*
                    Define some metadata about our api
                 */
                .apiProperty("api.title", "WildFly Swarm Camel REST API")
                .apiProperty("api.version", "1.2.3")
                .apiProperty("base.path", "/camel")
                /*
                    and enable CORS
                  */
                .apiProperty("cors", "true");
    }
}


Finally, we need to define a REST endpoint using the new DSL. This fluent API is used to describe how we interact with the endpoint, as well as exposing a number of methods that allow us to document the various aspects of the RESTful API.

package com.matthewcasperson.swarmdemo;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.apache.camel.model.rest.RestParamType;

import javax.ws.rs.core.MediaType;

/**
 * A camel route that uses the rest DSL
 */
class MyRoute extends RouteBuilder {

    @Override
    public void configure() {
        /*
            Create a rest endpoint
         */
        rest("/hello")
                /*
                    This is used by the swagger docs generator
                 */
                .description("An example of the Camel REST DSL")
                /*
                    We are returning plain text, so don't use the default binding
                    mode of JSON.
                 */
                .bindingMode(RestBindingMode.off)
                /*
                    response to get requests
                 */
                .get()
                /*
                    This is used by the swagger docs generator
                 */
                .description("A simple get endpoint with the REST DSL")
                /*
                    Document our query param
                 */
                .param()
                    .name("name")
                    .type(RestParamType.query)
                    .description("The name to be displayed in the output of this request")
                    .endParam()
                /*
                    We produce plain text
                 */
                .produces(MediaType.TEXT_PLAIN)
                /*
                    embed a camel route in rest dsl
                 */
                .route()
                /*
                    this is standard camel to set the contents of the message body
                 */
                .setBody(simple("Hello ${header.name}!"));
    }
}


When the Swarm application is run, you can access the Swagger documentation from http://localhost:8080/camel/api-docs. For a more human friendly view, past that URL into the Swagger UI available online at http://petstore.swagger.io/. Because we enabled CORS on our Swagger endpoint, the application will be able to read our API documentation and provide a nice interface to read the docs and interact with the API.

Image title

I have uploaded a version of this application to Heroku. You can view the Swagger JSON documentation at https://arcane-oasis-52239.herokuapp.com/camel/api-docs and execute the GET method at https://arcane-oasis-52239.herokuapp.com/camel/hello?name=Matt. Note that if you get a 404 the first time, try again in a few seconds as Heroku is probably still booting the application after it was suspended.

You can find the source code for this article at GitHub.

You can find articles in this series here.

The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

Topics:
restful api ,documentation ,camel ,rest dsl ,rest ,swagger ,api ,dsl ,restful

Published at DZone with permission of Matthew Casperson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}