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 RouteBuilder: rest("/orders").get("/{id}").to("direct:getOrder") says that GET /orders/{id} is handled by the route direct:getOrder. It is not an HTTP server itself. When the context starts, Camel turns each verb into an ordinary route whose consumer is an HTTP component, and that component does the listening:

  1. Each verb becomes a route that starts with a rest: endpoint for its method and path, such as rest:get:/orders:/{id}. The rest component hands it to the configured HTTP component, which registers the path with its server.
  2. 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.
  3. 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.
  4. The route's final message becomes the response: the body, the Content-Type header, and the status from CamelHttpResponseCode, 200 by default.

Which component listens depends on the runtime:

HTTP components behind the REST DSL
ComponentServerBest for
platform-httpThe runtime's own: Vert.x with Camel Main, Spring's web server with Spring BootMost applications in Camel 4
servletA servlet container, such as Spring Boot's TomcatSpring Boot applications that already use Spring MVC
netty-http, undertow, jettyAn embedded server of its ownStandalone 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-main, which starts a Vert.x HTTP server when camel.server.enabled=true. Each program picks a free port, starts Camel, calls its own API with java.net.http.HttpClient, prints requests and responses, and stops. Camel's logging is off.

A first REST API, and what the route sees

Two operations on /orders are enough to see how requests reach the routes, how query parameters become headers, and what happens to requests that match nothing:

Java
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()));
    }
}
Output
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>
  • GET /orders/7 reached direct:getOrder with the path parameter in the id header, and the method and path in CamelHttpMethod and CamelHttpPath.
  • The query parameter ?priority=high 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.
  • ?id=99 did not override the path parameter: the route still saw order 7.
  • The POST got 201 because the route set CamelHttpResponseCode. Without that, every successful response is 200.
  • DELETE /orders/7 got 405, Method Not Allowed: the path exists but has no delete() verb. /customers/1 matched no path and got 404 with a small HTML page from Vert.x.

The GET response had no Content-Type, because nothing set one. Declare produces() on the verb, or set the header in the route, so that clients know what they receive.

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 category, an optional limit with a default, and a POST that only accepts JSON:

Java
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()));
    }
}
Output
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 limit, the route saw the declared default, 10.
  • Without the required category, Camel answered 400 with Some of the required query parameters are missing., before the route ran. That check exists only because of clientRequestValidation(true). With the default, false, the same request reached the route and returned {"category":"","limit":10}, as running this program without the option shows.
  • Accept: text/xml got 406, Not Acceptable, because the verb declares produces("application/json").
  • A text/plain body sent to the POST got 415, Unsupported Media Type, because the verb declares consumes("application/json"). The 406 and 415 checks happened in this run with or without request validation.

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 limit of abc still reaches the route, which must check it: here it produced the invalid JSON {"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:

Java
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("")));
    }
}
Output
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
  • bindingMode(RestBindingMode.json) and type(NewOrder.class) made the route receive a NewOrder record, already parsed by Jackson, with its two lines.
  • The route returned an OrderCreated record, and the response was {"orderId":"A-17","items":4} with Content-Type: application/json, set by the binding.
  • The GET returned a List, which became a JSON array.
  • Broken JSON got 400 with an empty body: the binding failed before the route ran.
  • A valid order with one extra field, coupon, 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.

To accept unknown fields, add .dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES") to the REST configuration; with it, the last request in this program returns 200. The json.in. prefix applies the setting to request parsing, and json.out. to response writing. JSON binding needs a JSON data format on the classpath, here camel-jackson. The other modes are off (the default), xml, json_xml and auto.

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:

Java
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");
        }
    }
}
Output
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 OrderNotFound, and onException(OrderNotFound.class).handled(true) turned it into a normal response with status 404, a JSON content type and the message 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) is what makes the error handler's result the response; without it, the exception continues and the client gets the 500. Map each expected business failure to its own exception and status, and leave unexpected failures as 500s. The redelivery and matching rules of onException are on the Camel error handling page.

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() reads such a file, creates an HTTP endpoint for every operation, and sends each request to direct: plus the operation's operationId. This contract has three operations, but the program implements only two:

Java
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)" : ""));
    }
}
Output
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)
  • getOrder and placeOrder reached direct:getOrder and direct:placeOrder, with the path parameter in the id header as before.
  • getCustomer has no route. With missingOperation("ignore"), the request got 200 with an empty body, which a client cannot tell from a real empty answer. The default, fail, stops the application from starting with OpenAPI specification has 1 unmapped operations to corresponding routes: direct:getCustomer, which is safer. The third value, mock, answers with example data from files.
  • /invoices/1 is not in the contract, so it got 404.
  • apiContextPath("/api-doc") served the contract itself, all 35 lines, so clients can download the specification from the running service.

Contract-first REST is part of camel-rest-openapi. The code-first direction, generating an OpenAPI document from rest() declarations at restConfiguration().apiContextPath(...), needs the camel-openapi-java module, which was not available here, so it was not run.

REST configuration in Spring Boot

In Spring Boot, the same RouteBuilder classes work unchanged as @Component beans. The REST configuration can move to properties under camel.rest, defined by camel-core-starter. These settings were not run on this page; the Camel with Spring Boot page runs a REST route on Spring Boot 4.1:

Properties
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 camel-platform-http-starter, REST routes are served by Spring Boot's own web server on server.port, next to any Spring MVC controllers.
  • With camel-servlet-starter, they are served by Camel's servlet, by default under /camel/*, so /orders becomes /camel/orders. That prefix surprises many people moving from other runtimes.
  • context-path adds a prefix to every REST path.

Spring MVC's @RestController is the other way to build REST APIs in Spring Boot; it is covered on the Spring REST controller page. The REST DSL is the better fit when the request feeds an integration route anyway.

Choosing REST options

Common situations and the options that fit them
SituationOptions
JSON APIsbindingMode(json) with type() and outType()
Required parameters and media types enforced before the routeclientRequestValidation(true), param().required(true), consumes(), produces()
Clients that may send newer fieldsjson.in.disableFeatures=FAIL_ON_UNKNOWN_PROPERTIES
Status codes other than 200CamelHttpResponseCode in the route or in onException(...).handled(true)
An API agreed before it is builtrest().openApi().specification(...), keeping missingOperation at fail
Documentation generated from the codecamel-openapi-java and apiContextPath
Spring Bootcamel-platform-http-starter, or camel-servlet-starter under /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 Camel HTTP component page.