Apache Camel REST DSL: building HTTP APIs with routes
The REST DSL declares an HTTP API inside a RouteBuilder and sends each request into an ordinary Camel route. Its defaults decide which parameters are checked, which JSON is accepted, and what a client sees when a route fails. This page explains how REST declarations become routes, then runs a real HTTP server for each case.
Contents
How the REST DSL turns into routes
The REST DSL describes an HTTP API inside a RouteBuilderrest("/orders").get("/{id}").to("direct:getOrder")GET /orders/{id}direct:getOrder
- Each verb becomes a route that starts with a
endpoint for its method and path, such asrest: . Therest:get:/orders:/{id} component hands it to the configured HTTP component, which registers the path with its server.rest - The HTTP component receives a request, matches it to a path, and creates an exchange. Path parameters, query parameters and HTTP headers become message headers, and the request body becomes the message body.
- If a binding mode is set, the body is converted from JSON or XML into the declared Java type before the route runs, and the result is converted back afterwards.
- The route's final message becomes the response: the body, the
header, and the status fromContent-Type , 200 by default.CamelHttpResponseCode
Which component listens depends on the runtime:
| Component | Server | Best for |
|---|---|---|
platform-http | The runtime's own: Vert.x with Camel Main, Spring's web server with Spring Boot | Most applications in Camel 4 |
servlet | A servlet container, such as Spring Boot's Tomcat | Spring Boot applications that already use Spring MVC |
netty-httpundertowjetty | An embedded server of its own | Standalone applications that need that server's features |
The examples are complete programs for Camel 4.23 on Java 21. They use Camel Main with camel-platform-http-maincamel.server.enabled=truejava.net.http.HttpClient
A first REST API, and what the route sees
Two operations on /orders
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.slf4j.LoggerFactory;
public class FirstRest {
static String base;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
int port;
try (ServerSocket probe = new ServerSocket(0)) {
port = probe.getLocalPort(); // a free port for the HTTP server
}
base = "http://localhost:" + port;
Main main = new Main();
main.addInitialProperty("camel.server.enabled", "true");
main.addInitialProperty("camel.server.port", String.valueOf(port));
main.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
rest("/orders")
.get("/{id}").to("direct:getOrder")
.post().to("direct:createOrder");
from("direct:getOrder")
.setBody(simple("order ${header.id}, method ${header.CamelHttpMethod},"
+ " path ${header.CamelHttpPath},"
+ " priority header ${header.priority}"));
from("direct:createOrder")
.setHeader("CamelHttpResponseCode", constant(201))
.setBody(simple("created from '${body}'"));
}
});
main.start();
call("GET", "/orders/7", null);
call("GET", "/orders/7?priority=high", null);
call("GET", "/orders/7?id=99", null);
call("POST", "/orders", "2 x book");
call("DELETE", "/orders/7", null);
call("GET", "/customers/1", null);
main.stop();
}
static void call(String method, String path, String body) throws Exception {
HttpRequest request = HttpRequest.newBuilder(URI.create(base + path))
.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(method + " " + path + " -> " + response.statusCode()
+ (response.body().isEmpty() ? "" : ": " + response.body()));
}
}
GET /orders/7 -> 200: order 7, method GET, path /orders/7, priority header
GET /orders/7?priority=high -> 200: order 7, method GET, path /orders/7, priority header high
GET /orders/7?id=99 -> 200: order 7, method GET, path /orders/7, priority header
POST /orders -> 201: created from '2 x book'
DELETE /orders/7 -> 405
GET /customers/1 -> 404: <html><body><h1>Resource not found</h1></body></html>
reachedGET /orders/7 with the path parameter in thedirect:getOrder header, and the method and path inid andCamelHttpMethod .CamelHttpPath- The query parameter
also became a header. Any client can add query parameters, so a route that reads headers for its own purposes can be steered by them. Treat every header in a REST route as input from the client.?priority=high did not override the path parameter: the route still saw?id=99 .order 7- The
got 201 because the route setPOST . Without that, every successful response is 200.CamelHttpResponseCode got 405, Method Not Allowed: the path exists but has noDELETE /orders/7 verb.delete() matched no path and got 404 with a small HTML page from Vert.x./customers/1
The GETContent-Typeproduces()
Parameters, validation and content types
Verbs can declare their parameters, with types, defaults and whether they are required, and the media types they accept and return. This product search has a required categorylimitPOST
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.model.rest.RestParamType;
import org.slf4j.LoggerFactory;
public class Parameters {
static String base;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
int port;
try (ServerSocket probe = new ServerSocket(0)) {
port = probe.getLocalPort();
}
base = "http://localhost:" + port;
Main main = new Main();
main.addInitialProperty("camel.server.enabled", "true");
main.addInitialProperty("camel.server.port", String.valueOf(port));
main.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
restConfiguration().clientRequestValidation(true);
rest("/products")
.get().produces("application/json")
.param().name("category").type(RestParamType.query)
.required(true).endParam()
.param().name("limit").type(RestParamType.query)
.dataType("integer").defaultValue("10").endParam()
.to("direct:search")
.post().consumes("application/json").produces("application/json")
.to("direct:create");
from("direct:search")
.setBody(simple("{\"category\":\"${header.category}\","
+ "\"limit\":${header.limit}}"));
from("direct:create")
.setBody(constant("{\"created\":true}"));
}
});
main.start();
call("GET", "/products?category=books", null, null, null);
call("GET", "/products?category=books&limit=3", null, null, null);
call("GET", "/products", null, null, null);
call("GET", "/products?category=books", null, "text/xml", null);
call("POST", "/products", "{\"name\":\"pen\"}", null, "application/json");
call("POST", "/products", "name=pen", null, "text/plain");
main.stop();
}
static void call(String method, String path, String body, String accept,
String contentType) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(body));
if (accept != null) {
request.header("Accept", accept);
}
if (contentType != null) {
request.header("Content-Type", contentType);
}
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request.build(), HttpResponse.BodyHandlers.ofString());
System.out.println(method + " " + path
+ (accept == null ? "" : " (Accept: " + accept + ")")
+ (contentType == null ? "" : " (Content-Type: " + contentType + ")")
+ " -> " + response.statusCode()
+ (response.body().isEmpty() ? "" : ": " + response.body()));
}
}
GET /products?category=books -> 200: {"category":"books","limit":10}
GET /products?category=books&limit=3 -> 200: {"category":"books","limit":3}
GET /products -> 400: Some of the required query parameters are missing.
GET /products?category=books (Accept: text/xml) -> 406
POST /products (Content-Type: application/json) -> 200: {"created":true}
POST /products (Content-Type: text/plain) -> 415
- Without a
, the route saw the declared default, 10.limit - Without the required
, Camel answered 400 withcategory , before the route ran. That check exists only because ofSome of the required query parameters are missing. . With the default,clientRequestValidation(true) , the same request reached the route and returnedfalse , as running this program without the option shows.{"category":"","limit":10} got 406, Not Acceptable, because the verb declaresAccept: text/xml .produces("application/json")- A
body sent to thetext/plain got 415, Unsupported Media Type, because the verb declaresPOST . The 406 and 415 checks happened in this run with or without request validation.consumes("application/json")
The parameter declarations also feed the API documentation, so declaring them pays off twice. Validation checks presence and media types, not the content of values: a limitabc{"category":"books","limit":abc}
JSON binding to Java types
With a binding mode, the REST DSL converts the request body to a Java object and the response object back to JSON, so routes work with types instead of strings. An order with lines is posted and a list of lines is returned; then two bad requests show what binding rejects:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.model.rest.RestBindingMode;
import org.slf4j.LoggerFactory;
public class JsonBinding {
public record OrderLine(String sku, int qty) {}
public record NewOrder(String customer, List<OrderLine> lines) {}
public record OrderCreated(String orderId, int items) {}
static String base;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
int port;
try (ServerSocket probe = new ServerSocket(0)) {
port = probe.getLocalPort();
}
base = "http://localhost:" + port;
Main main = new Main();
main.addInitialProperty("camel.server.enabled", "true");
main.addInitialProperty("camel.server.port", String.valueOf(port));
main.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
restConfiguration().bindingMode(RestBindingMode.json);
rest("/orders")
.post().type(NewOrder.class).outType(OrderCreated.class)
.to("direct:create")
.get().outType(OrderLine[].class).to("direct:list");
from("direct:create")
.process(e -> {
NewOrder order = e.getMessage().getBody(NewOrder.class);
System.out.println(" route got " + order);
int items = order.lines().stream().mapToInt(OrderLine::qty).sum();
e.getMessage().setBody(new OrderCreated("A-17", items));
});
from("direct:list")
.setBody(constant(List.of(new OrderLine("BOOK-1", 1),
new OrderLine("PEN-2", 3))));
}
});
main.start();
call("POST", "/orders", "{\"customer\":\"C-1\",\"lines\":[{\"sku\":\"BOOK-1\","
+ "\"qty\":1},{\"sku\":\"PEN-2\",\"qty\":3}]}", "application/json");
call("GET", "/orders", null, null);
call("POST", "/orders", "{\"customer\":", "application/json");
call("POST", "/orders", "{\"customer\":\"C-2\",\"lines\":[],\"coupon\":\"X\"}",
"application/json");
main.stop();
}
static void call(String method, String path, String body, String contentType)
throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path))
.method(method, body == null ? HttpRequest.BodyPublishers.noBody()
: HttpRequest.BodyPublishers.ofString(body));
if (contentType != null) {
request.header("Content-Type", contentType);
}
System.out.println(method + " " + path + (body == null ? "" : " " + body));
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request.build(), HttpResponse.BodyHandlers.ofString());
String body2 = response.body();
System.out.println(" -> " + response.statusCode() + " "
+ response.headers().firstValue("Content-Type").orElse("(no Content-Type)")
+ (body2.isEmpty() ? "" : ": " + body2.lines().findFirst().orElse("")));
}
}
POST /orders {"customer":"C-1","lines":[{"sku":"BOOK-1","qty":1},{"sku":"PEN-2","qty":3}]}
route got NewOrder[customer=C-1, lines=[OrderLine[sku=BOOK-1, qty=1], OrderLine[sku=PEN-2, qty=3]]]
-> 200 application/json: {"orderId":"A-17","items":4}
GET /orders
-> 200 application/json: [{"sku":"BOOK-1","qty":1},{"sku":"PEN-2","qty":3}]
POST /orders {"customer":
-> 400 text/plain; charset=utf-8
POST /orders {"customer":"C-2","lines":[],"coupon":"X"}
-> 400 text/plain; charset=utf-8
andbindingMode(RestBindingMode.json) made the route receive atype(NewOrder.class) record, already parsed by Jackson, with its two lines.NewOrder- The route returned an
record, and the response wasOrderCreated with{"orderId":"A-17","items":4} , set by the binding.Content-Type: application/json - The
returned aGET , which became a JSON array.List - Broken JSON got 400 with an empty body: the binding failed before the route ran.
- A valid order with one extra field,
, also got 400. Jackson rejects unknown properties by default, so a client that sends a field added in a newer API version breaks against an older server.coupon
To accept unknown fields, add .dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES")json.in.json.out.camel-jacksonoffxmljson_xmlauto
Status codes and error responses
A REST API must say what went wrong with the right status code, without telling the client more than it should know. Here one route maps a "not found" exception to a 404 with a JSON body, and another route fails with an exception whose message contains an internal database address:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.slf4j.LoggerFactory;
public class ErrorResponses {
static class OrderNotFound extends RuntimeException {
OrderNotFound(String id) {
super("no order " + id);
}
}
static String base;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
int port;
try (ServerSocket probe = new ServerSocket(0)) {
port = probe.getLocalPort();
}
base = "http://localhost:" + port;
Map<String, String> orders = Map.of("7", "2 x book");
Main main = new Main();
main.addInitialProperty("camel.server.enabled", "true");
main.addInitialProperty("camel.server.port", String.valueOf(port));
main.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
onException(OrderNotFound.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404))
.setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
.setBody(simple("{\"error\":\"${exception.message}\"}"));
rest("/orders")
.get("/{id}").to("direct:get")
.get("/{id}/invoice").to("direct:invoice");
from("direct:get")
.process(e -> {
String id = e.getMessage().getHeader("id", String.class);
if (!orders.containsKey(id)) {
throw new OrderNotFound(id);
}
e.getMessage().setBody(orders.get(id));
});
from("direct:invoice")
.throwException(new IllegalStateException(
"invoice service failed: jdbc:postgresql://db-7:5432/billing"));
}
});
main.start();
call("/orders/7");
call("/orders/8");
call("/orders/7/invoice");
main.stop();
}
static void call(String path) throws Exception {
HttpResponse<String> response = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create(base + path)).build(),
HttpResponse.BodyHandlers.ofString());
String body = response.body();
System.out.println("GET " + path + " -> " + response.statusCode() + " "
+ response.headers().firstValue("Content-Type").orElse("(no Content-Type)"));
body.lines().limit(3).forEach(line -> System.out.println(" " + line));
if (body.lines().count() > 3) {
System.out.println(" ... " + (body.lines().count() - 3) + " more lines");
}
}
}
GET /orders/7 -> 200 (no Content-Type)
2 x book
GET /orders/8 -> 404 application/json
{"error":"no order 8"}
GET /orders/7/invoice -> 500 text/plain; charset=utf-8
- Order 7 exists, so the route returned it with status 200.
- Order 8 does not exist. The route threw
, andOrderNotFound turned it into a normal response with status 404, a JSON content type and the messageonException(OrderNotFound.class).handled(true) .no order 8 - The invoice route threw an exception that nothing handled. The client got 500 with an empty body: the message with the database address stayed on the server, in the log.
handled(true)onException
Contract first: routes from an OpenAPI file
Instead of describing the API in Java and generating documentation from it, the API can be written first as an OpenAPI file, agreed with the clients, and then implemented. rest().openApi()direct:operationId
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.net.ServerSocket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.slf4j.LoggerFactory;
public class ContractFirst {
// the API contract, written first and shared with the clients
static final String SPEC = """
openapi: 3.0.3
info:
title: Order API
version: 1.2.0
paths:
/orders/{id}:
get:
operationId: getOrder
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'200':
description: The order
/orders:
post:
operationId: placeOrder
responses:
'201':
description: Created
/customers/{id}:
get:
operationId: getCustomer
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'200':
description: The customer
""";
static String base;
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
Path spec = Files.createTempFile("orders", ".yaml");
Files.writeString(spec, SPEC);
int port;
try (ServerSocket probe = new ServerSocket(0)) {
port = probe.getLocalPort();
}
base = "http://localhost:" + port;
Main main = new Main();
main.addInitialProperty("camel.server.enabled", "true");
main.addInitialProperty("camel.server.port", String.valueOf(port));
main.configure().addRoutesBuilder(new RouteBuilder() {
@Override
public void configure() {
// every operation in the contract is sent to direct:<operationId>
rest().openApi().specification("file:" + spec)
.missingOperation("ignore")
.apiContextPath("/api-doc");
from("direct:getOrder")
.setBody(simple("order ${header.id}"));
from("direct:placeOrder")
.setHeader("CamelHttpResponseCode", constant(201))
.setBody(constant("placed"));
// no route for getCustomer
}
});
main.start();
call("GET", "/orders/7");
call("POST", "/orders");
call("GET", "/customers/3");
call("GET", "/invoices/1");
call("GET", "/api-doc");
main.stop();
}
static void call(String method, String path) throws Exception {
HttpResponse<String> response = HttpClient.newHttpClient().send(
HttpRequest.newBuilder(URI.create(base + path))
.method(method, HttpRequest.BodyPublishers.noBody()).build(),
HttpResponse.BodyHandlers.ofString());
String body = response.body();
System.out.println(method + " " + path + " -> " + response.statusCode()
+ (body.isEmpty() ? "" : ": " + body.lines().findFirst().orElse(""))
+ (body.lines().count() > 1 ? " ... (" + body.lines().count() + " lines)" : ""));
}
}
GET /orders/7 -> 200: order 7
POST /orders -> 201: placed
GET /customers/3 -> 200
GET /invoices/1 -> 404
GET /api-doc -> 200: openapi: 3.0.3 ... (35 lines)
andgetOrder reachedplaceOrder anddirect:getOrder , with the path parameter in thedirect:placeOrder header as before.id has no route. WithgetCustomer , the request got 200 with an empty body, which a client cannot tell from a real empty answer. The default,missingOperation("ignore") , stops the application from starting withfail , which is safer. The third value,OpenAPI specification has 1 unmapped operations to corresponding routes: direct:getCustomer , answers with example data from files.mock is not in the contract, so it got 404./invoices/1 served the contract itself, all 35 lines, so clients can download the specification from the running service.apiContextPath("/api-doc")
Contract-first REST is part of camel-rest-openapirest()restConfiguration().apiContextPath(...)camel-openapi-java
REST configuration in Spring Boot
In Spring Boot, the same RouteBuilder@Componentcamel.restcamel-core-starter
camel.rest.component=platform-http
camel.rest.binding-mode=json
camel.rest.client-request-validation=true
camel.rest.context-path=/api
camel.rest.data-format-property[json.in.disableFeatures]=FAIL_ON_UNKNOWN_PROPERTIES
- With
, REST routes are served by Spring Boot's own web server oncamel-platform-http-starter , next to any Spring MVC controllers.server.port - With
, they are served by Camel's servlet, by default undercamel-servlet-starter , so/camel/* becomes/orders . That prefix surprises many people moving from other runtimes./camel/orders adds a prefix to every REST path.context-path
Spring MVC's @RestController
Choosing REST options
| Situation | Options |
|---|---|
| JSON APIs | bindingMode(json)type()outType() |
| Required parameters and media types enforced before the route | clientRequestValidation(true)param().required(true)consumes()produces() |
| Clients that may send newer fields | json.in.disableFeatures=FAIL_ON_UNKNOWN_PROPERTIES |
| Status codes other than 200 | CamelHttpResponseCodeonException(...).handled(true) |
| An API agreed before it is built | rest().openApi().specification(...)missingOperationfail |
| Documentation generated from the code | camel-openapi-javaapiContextPath |
| Spring Boot | camel-platform-http-startercamel-servlet-starter/camel/* |
The traps to remember are query parameters that arrive as headers, required parameters that are not checked unless validation is on, unknown JSON fields that are rejected, and operations in a contract that silently return 200 when they are ignored. To call other HTTP services from a route, see the