이 콘텐츠는 선택한 언어로 제공되지 않습니다.

Chapter 44. GraphQL


Only producer is supported

The GraphQL component is a GraphQL client that communicates over HTTP and supports queries and mutations, but not subscriptions. It uses the Apache HttpClient library.

44.1. Dependencies

When using camel-graphql component starter with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:

<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-graphql-starter</artifactId>
</dependency>
Copy to Clipboard

44.2. Configuring Options

Camel components are configured on two separate levels:

  • component level
  • endpoint level

44.2.1. Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level. For example, a component may have security settings, credentials for authentication, urls for network connection and so forth. Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.
  • in a configuration file (application.properties, *.yaml files, etc).
  • directly in the Java code.

44.2.2. Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
  • They allow externalizing the configuration from the code.
  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

44.3. Component Options

The GraphQL component supports 2 options, which are listed below.

NameDescriptionDefaultType

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

44.4. Endpoint Options

The GraphQL endpoint is configured using following URI syntax:

graphql:httpUri
Copy to Clipboard

With the following path and query parameters:

44.4.1. Path Parameters (1 parameters)

NameDescriptionDefaultType

httpUri (producer)

Required The GraphQL server URI.

 

URI

44.4.2. Query Parameters (12 parameters)

NameDescriptionDefaultType

operationName (producer)

The query or mutation name.

 

String

proxyHost (producer)

The proxy host in the format hostname:port.

 

String

query (producer)

The query text.

 

String

queryFile (producer)

The query file name located in the classpath.

 

String

queryHeader (producer)

The name of a header containing the GraphQL query.

 

String

variables (producer)

The JsonObject instance containing the operation variables.

 

JsonObject

variablesHeader (producer)

The name of a header containing a JsonObject instance containing the operation variables.

 

String

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

accessToken (security)

The access token sent in the Authorization header.

 

String

jwtAuthorizationType (security)

The JWT Authorization type. Default is Bearer.

Bearer

String

password (security)

The password for Basic authentication.

 

String

username (security)

The username for Basic authentication.

 

String

44.5. Message Body

If the variables and variablesHeader parameters are not set and the IN body is a JsonObject instance, Camel uses it as the variables for the operation. If the query and queryFile parameters are not set and the IN body is a String, Camel uses it as the query. Camel stores the GraphQL response from the external server on the OUT message body. All headers from the IN message are copied to the OUT message, so the headers are preserved during routing. Additionally, Camel adds the HTTP response headers as well to the OUT message headers.

44.6. Examples

44.6.1. Queries

Simple queries can be defined directly in the URI:

from("direct:start")
    .to("graphql://http://example.com/graphql?query={books{id name}}")
Copy to Clipboard

The body can also be used for the query:

from("direct:start")
    .setBody(constant("{books{id name}}"))
    .to("graphql://http://example.com/graphql")
Copy to Clipboard

The query can come from a header:

from("direct:start")
    .setHeader("myQuery", constant("{books{id name}}"))
    .to("graphql://http://example.com/graphql?queryHeader=myQuery")
Copy to Clipboard

More complex queries can be stored in a file and referenced in the URI as follows.

booksQuery.graphql file:

query Books {
  books {
    id
    name
  }
}
Copy to Clipboard

from("direct:start")
    .to("graphql://http://example.com/graphql?queryFile=booksQuery.graphql")
Copy to Clipboard

When the query file defines multiple operations, it is required to specify which one should be executed:

from("direct:start")
    .to("graphql://http://example.com/graphql?queryFile=multipleQueries.graphql&operationName=Books")
Copy to Clipboard

Queries with variables need to reference a JsonObject instance from the registry:

bookByIdQuery.graphql file:

query BookById($id: Int!) {
  bookById(id: $id) {
    id
    name
    author
  }
}
Copy to Clipboard

@BindToRegistry("bookByIdQueryVariables")
public JsonObject bookByIdQueryVariables() {
    JsonObject variables = new JsonObject();
    variables.put("id", "book-1");
    return variables;
}

from("direct:start")
    .to("graphql://http://example.com/graphql?queryFile=bookByIdQuery.graphql&variables=#bookByIdQueryVariables")
Copy to Clipboard

A query that accesses variables via the variablesHeader parameter:

from("direct:start")
    .setHeader("myVariables", () -> {
        JsonObject variables = new JsonObject();
        variables.put("id", "book-1");
        return variables;
    })
    .to("graphql://http://example.com/graphql?queryFile=bookByIdQuery.graphql&variablesHeader=myVariables")
Copy to Clipboard

44.6.2. Mutations

Mutations are like queries with variables. They specify a query and a reference to a variables' bean as follows:

addBookMutation.graphql file:

mutation AddBook($bookInput: BookInput) {
  addBook(bookInput: $bookInput) {
    id
    name
    author {
      name
    }
  }
}
Copy to Clipboard

@BindToRegistry("addBookMutationVariables")
public JsonObject addBookMutationVariables() {
    JsonObject bookInput = new JsonObject();
    bookInput.put("name", "Typee");
    bookInput.put("authorId", "author-2");
    JsonObject variables = new JsonObject();
    variables.put("bookInput", bookInput);
    return variables;
}

from("direct:start")
    .to("graphql://http://example.com/graphql?queryFile=addBookMutation.graphql&variables=#addBookMutationVariables")
Copy to Clipboard

44.7. Spring Boot Auto-Configuration

The component supports 3 options, which are listed below.

NameDescriptionDefaultType

camel.component.graphql.autowired-enabled

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

Boolean

camel.component.graphql.enabled

Whether to enable auto configuration of the graphql component. This is enabled by default.

 

Boolean

camel.component.graphql.lazy-start-producer

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

Boolean

맨 위로 이동
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다. 최신 업데이트를 확인하세요.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

Theme

© 2025 Red Hat