Home > Net >  How to simply return a String using Apache Camel REST DSL
How to simply return a String using Apache Camel REST DSL

Time:09-21

I'm trying to use the Apache Camel REST DSL to create a simple REST API that just is supposed to return a String when called.

However, while the code below was once working, the API seems to have changed

rest().get("/hello-world").produces(MediaType.APPLICATION_JSON_VALUE).route()
      .setBody(constant("Welcome to apache camel test ")).endRest();

route() does not exist anymore in Apache Camel 3.17.0

enter image description here

I've also tried

rest("/say")
    .get("/hello")
    .responseMessage(200, "Hello World");

But this returns an empty String instead of "Hello World"

The only thing that worked so far is by creating an extra route

rest("/say")
    .get("/hello")
    .to("direct:build-return-message");

from("direct:build-return-message")
    .setBody(simple("Hello World"));

But this can't be the preferred way.

How would you now set the response body with the latest API?

CodePudding user response:

Something like this maybe ?

rest()
    .get("/hello")
    .route()
    .process( e -> e.getMessage().setBody("Hello World") ) ;

CodePudding user response:

While you can no longer define a simple route that returns a string in Rest-DSL you can use camels language component to achieve something similar using constants, simple language or by using a file in resources folder.

rest("/api")
    .description("Some description")
    .get("/constant")
        .produces("text/plain")
        .to("language:constant:Hello world")
    .get("/simple")
        .produces("text/html")
        // Usage {{host}}:{{port}}/api/simple?name=Bob
        .to("language:simple:<html><body><h1>hello ${headers.name}</h1></body></html>")
    .get("/resource")
        .produces("text/html")
        // Displays project/src/main/resources/pages/hello.html
        .to("language:constant:resource:classpath:pages/hello.html")
;

It's unfortunate that examples for language-component are quite sparse as it looks like handy tool for bunch of little things.

  • Related