Apache Camel: How to Expose Rest API

Reading Time: 3 minutes

The Apache Camel DSL is a language that allows to configure the behaviour of the Camel Routing Engine.

Apache Camel: Expose Rest API we have To use the Rest DSL in Java DSL then just do as with regular Camel routes by extending the RouteBuilder and define the routes in the configure method.

A simple REST service can be defined as follows, where we use rest() to define the services as shown below:

There are two main types of DSL:

  • Java DSL
  • Spring XML Config

In this tutorial we will use Java DSL using Spring Boot and Expose the Rest API using Apache Camel.

Let’s Start with the project structure:

The pom.xml will be as follows-

 
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-spring-boot-starter</artifactId>
			<version>2.24.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-servlet-starter</artifactId>
			<version>2.24.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.camel</groupId>
			<artifactId>camel-jackson</artifactId>
			<version>2.24.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

	</dependencies>

	 
 

Entity:

student.java

package com.SpringCamelRestDSL.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import javax.persistence.*;

/**
 * The type Student.
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
public class Student {
    @Id
    @Column(name = "id", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;

    private String name;
    private String email;
    private String course;

}

Repository:

Student.Repo

package com.SpringCamelRestDSL.repositray;

import com.SpringCamelRestDSL.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * The interface Student repo.
 */
public interface StudentRepo extends JpaRepository<Student,Long>
{
}

Service:

StudentService.java

package com.SpringCamelRestDSL.service;

 import com.SpringCamelRestDSL.entity.Student;
import com.SpringCamelRestDSL.repositray.StudentRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

 import java.util.List;

/**
 * The type Student service.
 */
@Service
public class StudentService {


     @Autowired
    private StudentRepo studentRepo;

    /**
     * Add student student.
     *
     * @param student the student
     * @return the student
     */
    public Student addStudent(Student student) {
        return studentRepo.save(student);
    }

    /**
     * Gets students.
     *
     * @return the students
     */
    public List<Student> getStudents() {
        return studentRepo.findAll();
    }

}

Apache Camel Processor:

The process interface is used to implement consumers of message exchanges or to implement a Message Translator, and other use-cases.

Create the camel processor as follows-

package com.SpringCamelRestDSL.processer;

 import com.SpringCamelRestDSL.entity.Student;
import com.SpringCamelRestDSL.service.StudentService;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * The type Student processor.
 */
@Component
public class StudentProcessor implements Processor {

    @Autowired
    private StudentService service;

    @Override
    public void process(Exchange exchange) throws Exception {
        service.addStudent(exchange.getIn().getBody(Student.class));
    }}

Route Builder:

create the route builder that expose the rest API’s as follows:

in this below code we route two methods one is GET and second is POST:

we expose get method using /getStudents and post method using /addStudents.

package com.SpringCamelRestDSL.routes;

 import com.SpringCamelRestDSL.entity.Student;
import com.SpringCamelRestDSL.processer.StudentProcessor;
import com.SpringCamelRestDSL.service.StudentService;
import org.apache.camel.BeanInject;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

/**
 * The type Application resource.
 */
@Component
    public class RestApiRouteBuilder extends RouteBuilder {

         @Autowired
         private StudentService service;

         @BeanInject
         private StudentProcessor processor;

         @Override
         public void configure() throws Exception {
             restConfiguration().component("servlet").port(9090).host("localhost").bindingMode(RestBindingMode.json);
             
             //get method
             rest().get("/getStudent").produces(MediaType.APPLICATION_JSON_VALUE).route().setBody(() -> service.getStudents())
                     .endRest();

            //post method
            rest().post("/addStudent").consumes(MediaType.APPLICATION_JSON_VALUE).type(Student.class).outType(Student.class)
                    .route().process(processor).endRest();

         }
     }
Main method:
package com.SpringCamelRestDSL;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * The type Spring camel rest dsl application.
 */
@SpringBootApplication
public class SpringCamelRestDslApplication  {

	/**
	 * The entry point of application.
	 *
	 * @param args the input arguments
	 */
	public static void main(String[] args) {
		SpringApplication.run(SpringCamelRestDslApplication.class, args);
	}
	}

some important terms to remember-

restConfiguration():-

Apache Camel Processor:

The Processor interface is used to implement consumers of message exchanges or to implement a Message Translator, and other use-cases.

Notice that the processor is referred to by the class type MyProcessor.class in the route. Camel will during startup automatic create one new instance of the processor using Injector to be used during routing messages.

Route Builder: The RouteBuilder is a base class which is derived from to create routing rules using the DSL. Instances of RouteBuilder are then added to the CamelContext.

Conclusion:

In this tutorial we covered in detail about Apache Camel and java DSL . how we can expose rest API’s using Java DSL and Apache camel. this tutorial will be very helpful for beginners.

Download Sorce Code: https://github.com/knoldus/Apache-Camel-SpringBoot-REST-API

Written by 

I'm a Software Consultant at Knoldus Inc. I have done Post Graduation from Quantum University Roorkee. I have knowledge of various programming languages. I'm passionate about Java development and curious to learn Java Technologies. I'm always ready to learn new technologies and my hobbies are cricket and action movies.