Apache Camel #2 - Calling Rest API

djoleb

Djordje Bajic

Posted on May 30, 2019

Apache Camel #2 - Calling Rest API

Hello!

This is the second text about Apache Camel, there will be a lot more in the future. Purpose of this articles is to present people the real power of Camel, maybe some of you will find a use case where you can use this framework instead of writing boilerplate code over and over.

Today we will use Camel to call API endpoint and handle some of the exceptions.

Dependencies

Camel http dependency

Routes

Scheduler route

If you remember from introduction, this is a scheduler route, it will trigger a message every 120 seconds and send it to "direct:httpRoute" route. I am using synchronous "direct" component, there is also asynchronous "seda" component.

@Override"
public void configure() {

    from("timer:scheduler?period=120000")
            .log("Scheduled job!")
            .to("direct:httpRoute");

}
Enter fullscreen mode Exit fullscreen mode

Http route

This is a HTTP client route, it will call the bittrex rest API and get crypto currencies and log the response.

@Override
public void configure() {

    from("direct:httpRoute")
            .log("Http Route started")
            .setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.GET)
            .to("https://api.bittrex.com/api/v1.1/public/getcurrencies")
            .log("Response : ${body}");

}
Enter fullscreen mode Exit fullscreen mode

Error Handlers

If you want to cover some exceptions there is a two options.

  1. Default error handler
  2. onException clause to handle specific class exceptions.

@Override
public void configure() {

    errorHandler(deadLetterChannel("mock:errorHandler"));

    onException(HttpOperationFailedException.class)
            .log("${exception}")
            .to("mock:errorHandler");

    from("direct:httpRoute")
            .log("Http Route started")
            .setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.GET)
            .to("https://api.bittrex.com/api/v1.1/public/getcurrencies")
            .log("Response : ${body}");

}
Enter fullscreen mode Exit fullscreen mode

Results

This is all for this tutorial, if something is not clear, feel free to contact me I will gladly answer any question.

Thanks!

💖 💪 🙅 🚩
djoleb
Djordje Bajic

Posted on May 30, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Apache Camel #2 - Calling Rest API
apachecamel Apache Camel #2 - Calling Rest API

May 30, 2019