Apache Camel #2 - Calling Rest API
Djordje Bajic
Posted on May 30, 2019
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
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.
- Default error handler
- 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 May 30, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.