Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Spark-rest Component

Available as of Camel 2.14

The Spark-rest component allows to define REST endpoints using the Spark REST Java library which has a nice DSL.

...

Code Block
xml
xml
	<dependency>
    	<groupId>org.apache.camel</groupId>
    	<artifactId>camel-spark-spark<rest</artifactId>
    	<version>${camel-version}</version>
	</dependency>

URI format

Code Block
  spark-rest://verb:path?[options]

URI Options

Wiki Markup
{div:class=confluenceTableSmall}
|| Name || Default Value || Description ||
| verb |  | get, post, put, patch, delete, head, trace, connect, or options. |
| path | | the content path which support Spark syntax. See further below for examples. |
| accept | */* | accept type such as: 'text/xml', or 'application/json'. By default we accept all kinds of types. |
{div}

Path using Spark syntax

The path option is defined using a Spark REST syntax where you define the REST context path using support for parameters and splat. See more details at the Spark Java Route documentation.

The following is a Camel route using a fixed path

Code Block
  from("spark-rest:get:hello")
    .transform().constant("Bye World");

And the following route uses a parameter which is mapped to a Camel header with the key "me".

Code Block
  from("spark-rest:get:hello/:me")
    .transform().simple("Bye ${header.me}");

Mapping to Camel Message

The Spark Request object is mapped to a Camel Message as a orgorg.apache.camel.component.sparksparkrest.SparkMessage which has access to the raw Spark request using the getRequest method. By default the Spark body is mapped to Camel message body, and any HTTP headers / Spark parameters is mapped to Camel Message headers. There is special support for the Spark splat syntax, which is mapped to the Camel message header with key splat.

For example the given route below uses Spark splat (the asterisk sign) in the context path which we can access as a header form the Simple language to construct a response message.

Code Block
  from("spark-rest:get:/hello/*/to/*")
    .transform().simple("Bye big ${header.splat[1]} from ${header.splat[0]}");

SparkRouteBuilder

If you use Java code, then you can use the class org.apache.camel.component.sparksparkrest.SparkRouteBuilder to define routes using a Spark DSL, as shown below

...

Code Block
  return new SparkRouteBuilder() {
      @Override
      public void configure() throws Exception {
            get("hello/:me")
                .transform().simple("Bye ${header.me}");
        }
    };

When using the SparkRouteBuilder, then you can define Camel routes using the REST verbs, such as get, post, put, delete etc.

More examples

There is a camel-example-spark-rest-tomcat example in the Apache Camel distribution, that demonstrates how to use camel-spark-rest in a web application that can be deployed on Apache Tomcat, or similar web containers.

...