Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

In this tutorial, we’ll build a small application using Apache Camel to expose both GraphQL and REST APIs. Apache Camel is a powerful integration framework that simplifies connecting different systems, including APIs, databases, and messaging services.

2. Setting up the Project

First, in our pom.xml file, let’s add dependencies for Camel core, Jetty, GraphQL, and Jackson:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-core</artifactId>
    <version>4.11.0</version>
</dependency>
<dependency>
    <groupId>com.graphql-java</groupId>
    <artifactId>graphql-java</artifactId>
    <version>23.1</version>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-jetty</artifactId>
    <version>4.11.0</version>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-graphql</artifactId>
    <version>4.11.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.18.0</version>
</dependency>

These dependencies bring in the necessary components to build the application. camel-jetty allows us to expose HTTP endpoints using Jetty as the embedded web server, while camel-graphql is used for serving GraphQL queries.

Lastly, Jackson is needed to handle JSON serialization and deserialization.

3. Creating the Book Model

We’ll create a simple model class called Book. This class represents the data we want to return in our APIs:

public class Book {
    private String id;
    private String title;
    private String author;

    // constructor, getter and setter methods
}

4. Creating a Service Class

Next, we create a BookService class that returns a list of books. We’re mocking the data for simplicity:

public class BookService {
    private final List<Book> books = new ArrayList<>();

    public BookService() {
        books.add(new Book("1", "Clean Code", "Robert"));
        books.add(new Book("2", "Effective Java", "Joshua"));
    }

    public List<Book> getBooks() {
        return books;
    }

    public Book getBookById(String id) {
        return books.stream().filter(b -> b.getId().equals(id)).findFirst().orElse(null);
    }

    public Book addBook(Book book) {
        books.add(book);
        return book;
    }
}

This service provides three main operations: retrieve all books, get a book by ID, and add a new book.

5. Creating REST Endpoints With Camel

We’ll expose RESTful endpoints using Apache Camel with Jetty as the embedded web server. Camel simplifies defining HTTP endpoints and routing logic through a RouteBuilder.

Let’s begin by defining a route in a class called BookRoute:

public class BookRoute extends RouteBuilder {
    private final BookService bookService = new BookService();

    @Override
    public void configure() {
        onException(Exception.class)
          .handled(true)
          .setHeader("Content-Type", constant("application/json"))
          .setBody(simple("{\"error\": \"${exception.message}\"}"));
        restConfiguration()
          .component("jetty")
          .host("localhost")
          .port(8080)
          .contextPath("/api")
          .bindingMode(RestBindingMode.json);

        //...
    }
}

The configure() method is where all route definitions live. Camel calls this during initialization to build the processing pipeline. We use the onException() method to create a global exception handler that catches any unhandled exceptions thrown during request processing.

restConfiguration() defines the server settings. We use Jetty on port 8080 and set the binding mode to JSON so that Camel automatically converts Java objects to JSON responses.

The host and port settings determine where our API will be accessible, while the context path establishes a base URL prefix for all our endpoints.

Next, we’ll create three endpoints for managing Book resources:

  • GET /api/books: a GET endpoint for retrieving all books
  • GET /api/books/{id}: a GET endpoint for retrieving a book by ID
  • POST /api/books: a POST endpoint to add a new book

Let’s define our actual REST endpoints using rest():

rest("/books") 
  .get().to("direct:getAllBooks") 
  .get("/{id}").to("direct:getBookById")
  .post().type(Book.class).to("direct:addBook");

We now define the internal Camel routes for each operation:

  • from(“direct:getAllBooks”): When a request hits /api/books, this route is triggered. It calls bookService.getBooks() to return the list of books.
  • from(“direct:getBookById”): This route is triggered when the client requests a book by ID. The path variable id is automatically mapped to the Camel header id, which is passed to bookService.getBookById().
  • from(“direct:addBook”): When a POST request with a JSON body is received, Camel deserializes it to a Book object and invokes bookService.addBook() with it.

These connect the direct:* endpoints to the BookService methods:

from("direct:getAllBooks")
  .bean(bookService, "getBooks");

from("direct:getBookById")
  .bean(bookService, "getBookById(${header.id})");

from("direct:addBook")
  .bean(bookService, "addBook");

By leveraging Apache Camel’s fluent DSL, we’ve cleanly separated HTTP routing from business logic and provided a maintainable and extensible way to expose REST APIs.

6. Creating the GraphQL Schema

To add GraphQL support to our application, we start by defining the schema in a separate file named books.graphqls. This file uses the GraphQL Schema Definition Language (SDL), which allows us to describe the structure of our API in a simple, declarative format:

type Book {
  id: String!
  title: String!
  author: String
}

type Query {
  books: [Book]
  bookById(id: String!): Book
}

type Mutation {
  addBook(id: String!, title: String!, author: String): Book
}

The schema begins with a Book type, which represents the main entity in our system. It contains three fields: id, title, and author. The id and title fields are annotated with an exclamation mark (!), indicating that these fields are non-nullable.

Following the type definition, the Query type outlines the operations clients can perform to retrieve data. Specifically, it allows clients to fetch a list of all books using the books query or to retrieve a single book by its ID using the bookById query.

To allow clients to create new book entries, we add a Mutation type. The addBook mutation accepts two arguments—title (required) and author (optional)—and returns the newly created Book object.

Now we need to create a schema loader class that connects GraphQL queries to the Java service. We create a class called CustomSchemaLoader, which loads the schema, parses it into a registry, and defines how each GraphQL operation is resolved using data fetchers:

public class CustomSchemaLoader{
    private final BookService bookService = new BookService();

    public GraphQLSchema loadSchema() {
        try (InputStream schemaStream = getClass().getClassLoader().getResourceAsStream("books.graphqls")) {
            if (schemaStream == null) {
                throw new RuntimeException("GraphQL schema file 'books.graphqls' not found in classpath");
            }

            TypeDefinitionRegistry registry = new SchemaParser()
              .parse(new InputStreamReader(schemaStream));

            RuntimeWiring wiring = buildRuntimeWiring();
            return new SchemaGenerator().makeExecutableSchema(registry, wiring);

        } catch (Exception e) {
            logger.error("Failed to load GraphQL schema", e);
            throw new RuntimeException("GraphQL schema initialization failed", e);
        }
    }

    public RuntimeWiring buildRuntimeWiring() {
        return RuntimeWiring.newRuntimeWiring()
          .type("Query", builder -> builder
            .dataFetcher("books", env -> bookService.getBooks())
            .dataFetcher("bookById", env -> bookService.getBookById(env.getArgument("id"))))
          .type("Mutation", builder -> builder
            .dataFetcher("addBook", env -> {
                String id = env.getArgument("id");
                String title = env.getArgument("title");
                String author = env.getArgument("author");
                if (title == null || title.isEmpty()) {
                    throw new IllegalArgumentException("Title cannot be empty");
                }
                return bookService.addBook(new Book(id, title, author));
          }))
          .build();
    }
}

The dataFetcher() serves as a connector between the GraphQL queries or mutations and the actual methods in our service layer. For example, when a client queries books, the system internally calls bookService.getBooks().

Similarly, for the addBook mutation, the resolver extracts the title and author arguments from the request and passes them to the bookService.addBook(title, author).

7. Adding GraphQL Route

With our schema and service logic in place, the next step is to expose our GraphQL endpoint using Apache Camel. To achieve this, we define a Camel route that listens for incoming HTTP POST requests and delegates them to the GraphQL engine for processing.

We configure the route using the Jetty component to listen for HTTP requests at port 8080, specifically on the /graphql path:

from("jetty:http://localhost:8088/graphql?matchOnUriPrefix=true")
    .log("Received GraphQL request: ${body}")
    .convertBodyTo(String.class)
    .process(exchange -> {
        String body = exchange.getIn().getBody(String.class);
        try {
            Map<String, Object> payload = new ObjectMapper().readValue(body, Map.class);
            String query = (String) payload.get("query");
            if (query == null || query.trim().isEmpty()) {
                throw new IllegalArgumentException("Missing 'query' field in request body");
            }
            ExecutionInput executionInput = ExecutionInput.newExecutionInput()
              .query(query)
              .build();
            ExecutionResult result = graphQL.execute(executionInput);
            Map<String, Object> response = result.toSpecification();
            exchange.getIn().setBody(response);
        } catch (Exception e) {
            throw new RuntimeException("GraphQL processing error", e);
        }
    })
    .marshal().json(JsonLibrary.Jackson)
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"));

The route listens for HTTP POST requests sent to /graphql. It extracts the query field from the incoming payload and executes it against the loaded GraphQL schema. The result of the query is transformed into a standard GraphQL response format, followed by marshaled back into JSON.

8. Main Application Class

Now that the route is defined, we need a main class to bootstrap the application. This class is responsible for initializing the Camel context, registering the schema loader, adding routes, and keeping the server alive.

We create a class called CamelRestGraphQLApp with a main method that performs the necessary setup:

public class CamelRestGraphQLApp {
    public static void main(String[] args) throws Exception {
        CamelContext context = new DefaultCamelContext();
        context.addRoutes(new BookRoute());
        context.start();
        logger.info("Server running at http://localhost:8080");
        Thread.sleep(Long.MAX_VALUE);
        context.stop();
    }
}

This class registers the schema loader as a bean, adds the routes, and starts the server.

The Thread.sleep(LONG.MAX_VALUE) call is a simple way to keep the application running. In a production-grade application, this would be replaced with a more robust mechanism for managing the application lifecycle, but for demonstration purposes, this keeps the server alive to handle incoming requests.

9. Testing

We can write a test using Camel’s CamelContext and the ProducerTemplate to simulate sending HTTP requests:

@Test
void whenCallingRestGetAllBooks_thenShouldReturnBookList() {
    String response = template.requestBodyAndHeader(
      "http://localhost:8080/api/books",
      null,
      Exchange.CONTENT_TYPE,
      "application/json",
      String.class
    );

    assertNotNull(response);
    assertTrue(response.contains("Clean Code"));
    assertTrue(response.contains("Effective Java"));
}

@Test
void whenCallingBooksQuery_thenShouldReturnAllBooks() {
    String query = """
    {
        "query": "{ books { id title author } }"
    }""";

    String response = template.requestBodyAndHeader(
      "http://localhost:8080/graphql",
      query,
      Exchange.CONTENT_TYPE,
      "application/json",
      String.class
    );
    assertNotNull(response);
    assertTrue(response.contains("Clean Code"));
    assertTrue(response.contains("Effective Java"));
}

10. Conclusion

In this article, we successfully integrated both REST and GraphQL endpoints into our Camel application, enabling efficient management of book data through both query-based and mutation-based APIs.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

Course – LS – NPI (cat=REST)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)