Camel Components

GraphQL

Since Camel 3.0

Only producer is supported

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

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-graphql</artifactId>
    <version>x.x.x</version>
  <!-- use the same version as your Camel core version -->
</dependency>

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

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.

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.

Component Options

The GraphQL component supports the following options which are listed below.

Name Description Default Type

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

throwExceptionOnFailure (producer)

Whether to fail the exchange with an HttpOperationFailedException when the HTTP status code of the response is not 2xx. Set it to false to get the response body whatever the status code, with the code in the CamelHttpResponseCode header. GraphQL errors in a 2xx response do not fail the exchange.

true

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

httpClient (advanced)

A custom Apache HttpClient 5 (classic) to send the requests with, instead of one that the http component creates. The proxyHost, accessToken, username and password options, and the client settings of the http component, are not applied to it: configure them on the client itself.

HttpClient

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

HeaderFilterStrategy

Endpoint Options

The GraphQL endpoint is configured using URI syntax:

graphql:httpUri

With the following path and query parameters:

Path Parameters

Name Description Default Type

httpUri (producer)

Required The URL of the GraphQL endpoint of the server, such as http://example.com/graphql (http or https). Each request is an HTTP POST with a JSON body that holds the query, operationName and variables. Endpoint parameters that are not options of this component are added to the query string of this URL.

URI

Query Parameters

Name Description Default Type

headerFilterStrategy (common (advanced))

The HeaderFilterStrategy that decides which headers of the message are sent as HTTP request headers, and which HTTP response headers are set on the message. The default HttpHeaderFilterStrategy filters out the Camel headers and HTTP headers such as Content-Length and Host.

HeaderFilterStrategy

operationName (producer)

The name of the operation in the GraphQL document to execute, sent as the operationName field of the JSON body. GraphQL requires it when the document defines more than one operation.

String

proxyHost (producer)

The HTTP proxy to send the requests through, as hostname:port (the port is required). The connection to the proxy is plain HTTP, and an https request is tunneled through it with CONNECT. Proxy authentication cannot be configured with this option.

String

query (producer)

The GraphQL document to send, with the query or mutation to execute, as the query field of the JSON body. It takes precedence over queryFile, queryHeader and the message body.

String

queryFile (producer)

The resource with the GraphQL document to send, read once on the first message. A name without a prefix is loaded from the classpath; use the file: prefix for the file system, or another resource prefix such as http:. Not used when query is set; it takes precedence over queryHeader and the message body.

String

queryHeader (producer)

The name of a header with the GraphQL document to send, as text. Used when query and queryFile are not set, instead of the message body. The header is not sent as an HTTP header.

String

throwExceptionOnFailure (producer)

Whether to fail the exchange with an HttpOperationFailedException when the HTTP status code of the response is not 2xx. Set it to false to get the response body whatever the status code, with the code in the CamelHttpResponseCode header. GraphQL errors in a 2xx response do not fail the exchange.

true

boolean

variables (producer)

The variables of the operation, as a JsonObject (such as a reference to a bean in the registry), sent as the variables field of the JSON body. It takes precedence over variablesHeader and a Map body. Without variables, an empty JSON object is sent.

JsonObject

variablesHeader (producer)

The name of a header with the variables of the operation, as a Map such as a JsonObject. Used when variables is not set, and it takes precedence over a Map body. The header is not sent as an HTTP header.

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

httpClient (advanced)

A custom Apache HttpClient 5 (classic) to send the requests with, instead of one that the http component creates. The proxyHost, accessToken, username and password options, and the client settings of the http component, are not applied to it: configure them on the client itself.

HttpClient

accessToken (security)

The access token sent in the Authorization header of every request to the scheme, host and port of httpUri, as the jwtAuthorizationType followed by the token. The header is not added when the request already has an Authorization header, such as one from a header of the message.

String

jwtAuthorizationType (security)

The authorization scheme written before the accessToken in the Authorization header. The token does not need to be a JWT.

Bearer

String

password (security)

The password for HTTP authentication with the server, used together with username. Apache HttpClient sends the credentials only after the server answers with a 401 challenge (such as Basic or Digest), and only to the scheme, host and port of httpUri.

String

username (security)

The username for HTTP authentication with the server, used together with password. Apache HttpClient sends the credentials only after the server answers with a 401 challenge (such as Basic or Digest), and only to the scheme, host and port of httpUri.

String

Message Headers

The GraphQL component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelHttpResponseCode (producer)

Constant: HTTP_RESPONSE_CODE

The HTTP status code of the response of the GraphQL server, such as 200. It is also set when the exchange fails with an HttpOperationFailedException for a status code that is not 2xx.

int

CamelHttpResponseText (producer)

Constant: HTTP_RESPONSE_TEXT

The reason phrase of the HTTP response of the GraphQL server, such as OK.

String

Content-Type (producer)

Constant: CONTENT_TYPE

The Content-Type of the HTTP response of the GraphQL server, such as application/json, set after a call that got a response. The request is always sent as application/json, whatever this header of the message is.

String

Authorization (producer)

Constant: AUTHORIZATION

The HTTP Authorization header of the request, such as Bearer followed by a token. When the message has this header, it is sent as it is and the accessToken option does not add one.

String

Message Body

The message body at each side of the GraphQL component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Producer input

text, bytes, stream or file

The query, when none of query, queryFile and queryHeader is set: text, or bytes, a stream or a file of it; another body, such as a Map, fails. With one of them the body is not sent, except that a Map body, such as an org.apache.camel.util.json.JsonObject, is the variables when neither variables nor variablesHeader is set.

Not known when query or queryFile or queryHeader is set.

Producer output

text or null

The response as text, the JSON with the data and errors of GraphQL: unmarshal it to read them. Errors in the response do not fail the exchange; a status outside 2xx does, unless throwExceptionOnFailure=false, which keeps the response as text. null for a response without a body.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Message Body

If the query, queryFile and queryHeader parameters are not set, the body is the query: it must be text, bytes, a stream or a file, and another body (such as a Map) fails with an InvalidPayloadException. Otherwise, if the variables and variablesHeader parameters are not set and the body is a Map (such as a JsonObject), Camel will use it for the operation’s variables. Camel will store the GraphQL response from the external server on the message body, as a String of the JSON response, with the data and errors of GraphQL: errors in the response do not fail the exchange.

HTTP Headers

The headers of the message are sent as HTTP request headers (filtered by the headerFilterStrategy), except:

  • the headers named by the queryHeader and variablesHeader parameters, as the query and the variables are sent in the JSON body of the request;

  • a Content-Encoding header, as the request is not compressed.

The producer always sends the request with Content-Type: application/json, Accept: application/json and Accept-Encoding: gzip, whatever the headers of the message are.

After the call, the message keeps its own headers, and Camel adds the HTTP response headers (such as CamelHttpResponseCode and the Content-Type of the response). The headers the producer set for the request (CamelHttpMethod, Accept and Accept-Encoding) do not stay on the message: a header of the message with the same name keeps its value.

Examples

Queries

Simple queries can be defined directly in the URI:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("graphql://http://example.com/graphql?query={books{id name}}");
<route>
  <from uri="direct:start"/>
  <to uri="graphql://http://example.com/graphql?query={books{id name}}"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: graphql://http://example.com/graphql
            parameters:
              query: "{books{id name}}"

The body can also be used for the query:

  • Java

  • XML

  • YAML

from("direct:start")
    .setBody(constant("{books{id name}}"))
    .to("graphql://http://example.com/graphql");
<route>
  <from uri="direct:start"/>
  <setBody>
    <constant>{books{id name}}</constant>
  </setBody>
  <to uri="graphql://http://example.com/graphql"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - setBody:
            constant: "{books{id name}}"
        - to:
            uri: graphql://http://example.com/graphql

The query can come from a header also:

  • Java

  • XML

  • YAML

from("direct:start")
    .setHeader("myQuery", constant("{books{id name}}"))
    .to("graphql://http://example.com/graphql?queryHeader=myQuery");
<route>
  <from uri="direct:start"/>
  <setHeader name="myQuery">
    <constant>{books{id name}}</constant>
  </setHeader>
  <to uri="graphql://http://example.com/graphql?queryHeader=myQuery"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - setHeader:
            name: myQuery
            constant: "{books{id name}}"
        - to:
            uri: graphql://http://example.com/graphql
            parameters:
              queryHeader: myQuery

More complex queries can be stored in a file and referenced in the URI:

booksQuery.graphql file:

query Books {
  books {
    id
    name
  }
}
  • Java

  • XML

  • YAML

from("direct:start")
    .to("graphql://http://example.com/graphql?queryFile=booksQuery.graphql");
<route>
  <from uri="direct:start"/>
  <to uri="graphql://http://example.com/graphql?queryFile=booksQuery.graphql"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: graphql://http://example.com/graphql
            parameters:
              queryFile: booksQuery.graphql

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

  • Java

  • XML

  • YAML

from("direct:start")
    .to("graphql://http://example.com/graphql?queryFile=multipleQueries.graphql&operationName=Books");
<route>
  <from uri="direct:start"/>
  <to uri="graphql://http://example.com/graphql?queryFile=multipleQueries.graphql&amp;operationName=Books"/>
</route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: graphql://http://example.com/graphql
            parameters:
              queryFile: multipleQueries.graphql
              operationName: Books

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
  }
}
Java-only: registering query variables and referencing them in the endpoint
@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")

A query that accesses variables via the variablesHeader parameter:

Java-only: setting variables via a header with a lambda supplier
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")

Mutations

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

addBookMutation.graphql file:

mutation AddBook($bookInput: BookInput) {
  addBook(bookInput: $bookInput) {
    id
    name
    author {
      name
    }
  }
}
Java-only: registering mutation variables and referencing them in the endpoint
@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")