REST
Since Camel 2.14
Both producer and consumer are supported
The REST component allows defining REST endpoints (consumer) using the Rest DSL and plugin to other Camel components as the REST transport.
The REST component can also be used as a client (producer) to call REST services.
Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The REST component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
The name of the Camel component that runs the REST services, such as platform-http, servlet or jetty. The consumerComponentName option of an endpoint replaces it. If neither is set, the component of the rest configuration is used. | String | ||
The location of the OpenAPI document (JSON or YAML) of the REST service to call: a file, an http or https URL, or a classpath resource. The apiDoc option of an endpoint replaces it. If neither is set, the producerApiDoc of the rest configuration is used. | String | ||
The scheme, host and port of the REST service to call, with an optional base path, such as http://myserver:8080/foo. The host option of an endpoint replaces it. If neither is set, the host and port of the rest configuration are used. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | |
The name of the Camel component that sends the HTTP requests, such as http or vertx-http. The producerComponentName option of an endpoint replaces it. If neither is set, the producerComponent of the rest configuration is used. | String | ||
Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | |
To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy |
Endpoint Options
The REST endpoint is configured using URI syntax:
rest:method:path:uriTemplate
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The HTTP method of the REST service. The consumer answers requests with this method, and the producer sends the request with it. Enum values:
| String | ||
Required The base path of the REST service, such as users. Without uriTemplate, it is the whole path, and it can hold {name} path parameters as in uriTemplate. A consumer can end it with * to match all the paths that start with it. | String | ||
The path below the base path, such as {id}, which can hold {name} path parameters. The consumer sets each path parameter of a request as a header. The producer fills each {name} with the header of that name, or else the exchange variable of that name. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The media types, separated by comma, that this endpoint takes in, such as application/json. For the consumer, the media types of the request body that the REST service accepts. The producer sets it as the Accept header of the request when the message has no Accept header. | String | ||
The class name of the request body, with [] appended for an array. The consumer stores it in the rest registry. With xml binding, the producer uses it as the JAXB context of the request body. | String | ||
The class name of the response body, with [] appended for an array. With a binding mode other than off, the producer reads a JSON or XML response into this class, and without it the producer does not read the response. The consumer stores it in the rest registry. | String | ||
The media types, separated by comma, that this endpoint sends, such as application/json. For the consumer, the media types of the response body that the REST service returns. The producer sets it as the Content-Type header of the request when the message has no Content-Type header. | String | ||
The id of the route of this REST service, which the consumer stores in the rest registry to count the requests of the service. The Rest DSL sets it to the id of the route that it creates. This option does not set the id of the route. | String | ||
The name of the Camel component that runs the REST service, such as platform-http, servlet or jetty. If not set, the component of the rest configuration is used. If that is not set either, the consumer takes the first component of the CamelContext that is a RestConsumerFactory, then platform-http, then a single RestConsumerFactory in the registry, then servlet, jetty, undertow, netty-http or coap, whichever is on the classpath. | String | ||
A description of this REST service, which the consumer stores in the rest registry. The Rest DSL sets it from the description of the route, the verb or the rest. | String | ||
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | |
To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | ExceptionHandler | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
The location of the OpenAPI document (JSON or YAML) of the REST service to call: a file, an http or https URL, or a classpath resource. When set, the producer needs camel-openapi-java, and fails to start if the document has no operation for the method and path. If not set, the apiDoc option of the component, or else the producerApiDoc of the rest configuration, is used. | String | ||
The binding mode of the producer, which replaces the bindingMode of the rest configuration (off by default). With json, xml or json_xml, the producer writes a POJO body as JSON or XML, and reads the response into outType. With auto, it chooses from the Content-Type header, and sends or keeps a body that it cannot bind as it is. Enum values:
| RestBindingMode | ||
The scheme, host and port of the REST service to call, with an optional base path, such as http://myserver:8080/foo. The scheme is http when it is not given. If not set, the host option of the component, or else the host and port of the rest configuration, is used. The producer fails to start without a host. | String | ||
The name of the Camel component that sends the HTTP request, such as http or vertx-http. If not set, the producerComponent of the rest configuration is used. If that is not set either, the producer takes the first component of the CamelContext that is a RestProducerFactory, then the component of consumerComponentName, then a single RestProducerFactory in the registry, then http, vertx-http, undertow or netty-http, whichever is on the classpath. | String | ||
The query string of the request, such as foo=123&bar=456. A value {name} is filled with the header or the exchange variable of that name, and a parameter with the value \{name?} is left out when neither is set. The endpoint also adds the parameters of its URI that it does not know, except the options of the component that sends the HTTP request. | String | ||
Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean |
Message Headers
The REST component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The query string of the request. The producer sets it from the queryParameters option, with the {name} values filled in. The HTTP producer uses it in place of the query of its endpoint. | String | |
| Constant: | The URI of the request, with the path parameters filled in. The producer sets it when it fills a path parameter from a header or a variable, and then removes the CamelHttpPath header. The HTTP producer uses it in place of the URI of its endpoint. | String | |
| Constant: | The HTTP method of the request, in upper case. The producer sets it from the method of the endpoint, and replaces any value that the message has. | String | |
| Constant: | The media type of the request body. The producer sets it to the produces option when the message has no Content-Type header. With binding, the producer reads it to choose between JSON and XML. | String | |
| Constant: | The media types that the response may have. The producer sets it to the consumes option when the message has no Accept header. | String | |
CamelHttpResponseCode (producer) Constant: | The HTTP status code of the response, which the HTTP producer sets. With binding, the producer does not read a response with a code of 300 or more into outType, unless skipBindingOnErrorCode of the rest configuration is false. | Integer |
Message Body
The message body at each side of the REST component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The request body as the HTTP consumer gives it (platform-http by default). With bindingMode json, the object of inType, or a Map or a List without inType.
Not known when |
Consumer reply |
| The response body as the HTTP consumer writes it. With bindingMode json, any object, which the binding writes as JSON.
Not known when |
Producer input |
| The request body the HTTP producer sends (the http component by default). With bindingMode json, any object, which the binding writes as JSON.
Not known when |
Producer output |
| The response body as the HTTP producer gives it; with bindingMode json and outType, an object of outType. Not known when |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Supported REST components
The following components support the REST consumer (Rest DSL):
-
camel-netty-http
-
camel-jetty
-
camel-servlet
-
camel-undertow
-
camel-platform-http
The following components support the REST producer:
-
camel-http
-
camel-netty-http
-
camel-undertow
-
camel-vertx-http
Usage
Path and uriTemplate syntax
The path and uriTemplate option is defined using a REST syntax where you define the REST context path using support for parameters.
| If no uriTemplate is configured then It does not matter if you configure only |
The following is a Camel route using a path only
-
Java
-
XML
-
YAML
from("rest:get:hello")
.transform().constant("Bye World"); <route>
<from uri="rest:get:hello"/>
<transform>
<constant>Bye World</constant>
</transform>
</route> - route:
from:
uri: rest:get:hello
steps:
- transform:
constant: "Bye World" And the following route uses a parameter which is mapped to a Camel header with the key "me".
-
Java
-
XML
-
YAML
from("rest:get:hello/{me}")
.transform().simple("Bye ${header.me}"); <route>
<from uri="rest:get:hello/{me}"/>
<transform>
<simple>Bye ${header.me}</simple>
</transform>
</route> - route:
from:
uri: rest:get:hello/{me}
steps:
- transform:
simple: "Bye ${header.me}" The following examples have configured a base path as "hello" and then have two REST services configured using uriTemplates.
-
Java
-
XML
-
YAML
from("rest:get:hello:/{me}")
.transform().simple("Hi ${header.me}");
from("rest:get:hello:/french/{me}")
.transform().simple("Bonjour ${header.me}"); <route>
<from uri="rest:get:hello:/{me}"/>
<transform>
<simple>Hi ${header.me}</simple>
</transform>
</route>
<route>
<from uri="rest:get:hello:/french/{me}"/>
<transform>
<simple>Bonjour ${header.me}</simple>
</transform>
</route> - route:
from:
uri: rest:get:hello:/{me}
steps:
- transform:
simple: "Hi ${header.me}"
- route:
from:
uri: rest:get:hello:/french/{me}
steps:
- transform:
simple: "Bonjour ${header.me}" Examples
Rest producer examples
You can use the REST component to call REST services like any other Camel component.
For example, to call a REST service on using hello/{me} you can do
-
Java
-
XML
-
YAML
from("direct:start")
.to("rest:get:hello/{me}"); <route>
<from uri="direct:start"/>
<to uri="rest:get:hello/{me}"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: rest:get:hello/{me} And then the dynamic value {me} is mapped to a header or variable with the same name. So to call this REST service, you can send an empty message body and a header as shown:
template.sendBodyAndHeader("direct:start", null, "me", "Donald Duck"); Instead of a header you can also use exchange variable such as:
String response = template.withVariable("me", "Donald Duck").to("direct:start").request(String.class); The Rest producer needs to know the hostname and port of the REST service, which you can configure using the host option as shown:
-
Java
-
XML
-
YAML
from("direct:start")
.to("rest:get:hello/{me}?host=myserver:8080/foo"); <route>
<from uri="direct:start"/>
<to uri="rest:get:hello/{me}?host=myserver:8080/foo"/>
</route> - route:
from:
uri: direct:start
steps:
- to:
uri: rest:get:hello/{me}
parameters:
host: "myserver:8080/foo" Instead of using the host option, you can configure the host on the restConfiguration as shown:
restConfiguration().host("myserver:8080/foo");
from("direct:start")
.to("rest:get:hello/{me}"); You can use the producerComponent to select which Camel component to use as the HTTP client, for example to use http, you can do:
restConfiguration().host("myserver:8080/foo").producerComponent("http");
from("direct:start")
.to("rest:get:hello/{me}"); The parameters of the endpoint URI that are not options of the rest endpoint are sent as query parameters of the request, except the options of the component that sends the request. For example, with http as the producer component, the following route calls http://myserver:8080/foo/hello/{me}?page=2, and logs in with the authUsername and authPassword options of the http component. This is the same whether the producer component is set with the producerComponentName option, with the producerComponent of the rest configuration, or is detected automatically. To send a query parameter that has the same name as an option of the producer component, set it in the queryParameters option.
restConfiguration().host("myserver:8080/foo").producerComponent("http");
from("direct:start")
.to("rest:get:hello/{me}?page=2&authUsername=scott&authPassword=RAW(tiger)"); Rest producer binding
The REST producer supports binding using JSON or XML like the rest-dsl does.
For example, to use jetty with JSON binding mode turned on, you can configure this in the REST configuration:
restConfiguration().component("jetty").host("localhost").port(8080).bindingMode(RestBindingMode.json);
from("direct:start")
.to("rest:post:user"); Then when calling the REST service using the REST producer, it will automatically bind any POJOs to JSON before calling the REST service:
UserPojo user = new UserPojo();
user.setId(123);
user.setName("Donald Duck");
template.sendBody("direct:start", user); In the example above we send a POJO instance UserPojo as the message body. And because we have turned on JSON binding in the REST configuration, then the POJO will be marshalled from POJO to JSON before calling the REST service.
However, if you want to also perform binding for the response message (e.g., what the REST service sends back, as response) you would need to configure the outType option to specify what is the class name of the POJO to unmarshal from JSON to POJO.
For example, if the REST service returns a JSON payload that binds to com.foo.MyResponsePojo you can configure this as shown:
restConfiguration().component("jetty").host("localhost").port(8080).bindingMode(RestBindingMode.json);
from("direct:start")
.to("rest:post:user?outType=com.foo.MyResponsePojo"); You must configure outType option if you want POJO binding to happen for the response messages received from calling the REST service. |
More examples
See Rest DSL, which offers more examples and how you can use the Rest DSL to define those in a nicer, restful way.
There is a camel-example-servlet-rest-tomcat example in the Apache Camel distribution, that demonstrates how to use the Rest DSL with Servlet as transport that can be deployed on Apache Tomcat, or similar web containers.