loading...
Cover image for Apache Camel #2 - Calling Rest API

Apache Camel #2 - Calling Rest API

djoleb profile image Djordje Bajic Updated on 惻2 min read

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");

}

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}");

}

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}");

}

Results

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

Thanks!

Posted on by:

djoleb profile

Djordje Bajic

@djoleb

Java backend engineer @ Humanity inc.

Discussion

pic
Editor guide
 

Hi Djordje,

i am a beginner with Camel. Can you give me a tip how to parse the Rest Response. For Example instead of the .log("Response : ${body}") in the above Code, i would like to parse the Response, convert the Json structure and reply back to the caller.