Chapter 3. REST DSL in Red Hat build of Apache Camel for Quarkus
Apache Camel offers a REST styled DSL which you can use to define REST services (hosted by Camel) using a REST style with verbs such as get, post, delete, and so on.
3.1. How it works Copy linkLink copied to clipboard!
The REST DSL is a facade that builds Rest endpoints as consumers for Camel routes. The actual REST transport is leveraged by using Camel REST components such as Netty HTTP, Servlet, and others that have native REST integration.
3.2. Components supporting REST DSL Copy linkLink copied to clipboard!
The following Camel components support the REST DSL:
camel-rest required
- contains the base rest component needed by REST DSL
- camel-netty-http
- camel-jetty
- camel-platform-http recommended
- camel-servlet
- camel-undertow
3.3. REST DSL with code first Copy linkLink copied to clipboard!
This section describes a code-first approach to working with REST DSL.
For a more modern contract-first approach, see the REST DSL with OpenAPI contract first
3.3.1. REST DSL with Java DSL Copy linkLink copied to clipboard!
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:
This defines a REST service with the following url mappings:
| Base Path | Uri template | Verb | Consumes |
|---|---|---|---|
|
|
|
| all |
|
|
|
|
|
|
|
|
| all |
Notice that in the REST service we route directly to a Camel endpoint using to(). This is because the REST DSL has a shorthand for routing directly to an endpoint using to().
3.3.2. REST DSL with XML DSL Copy linkLink copied to clipboard!
The example above can be defined in XML as shown below:
3.3.3. Using a base path Copy linkLink copied to clipboard!
The REST DSL allows defining a base path to help applying the "don’t repeat yourself" (DRY) practice. For example, to define a customer path, we can set the base path in rest("/customer") and then provide the uri templates in the verbs, as shown below:
rest("/customers/")
.get("/{id}").to("direct:customerDetail")
.get("/{id}/orders").to("direct:customerOrders")
.post("/neworder").to("direct:customerNewOrder");
rest("/customers/")
.get("/{id}").to("direct:customerDetail")
.get("/{id}/orders").to("direct:customerOrders")
.post("/neworder").to("direct:customerNewOrder");
And using XML DSL, it becomes:
The REST DSL will take care of duplicate path separators when using base path and uri templates. In the example above the rest base path ends with a slash / and the verb starts with a slash /. Camel will take care of this and remove the duplicated slash.
It is not required to use both base path and uri templates. You can omit the base path and define the base path and uri template in the verbs only. The example above can be defined as:
You can combine path parameters to build complex expressions. For example:
rest("items/")
.get("{id}/{filename}.{content-type}")
.to("direct:item")
rest("items/")
.get("{id}/{filename}.{content-type}")
.to("direct:item")
3.3.4. Managing REST services Copy linkLink copied to clipboard!
Each of the rest services becomes a Camel route, so in the first example, we have 2 x get and 1 x post REST service, which each becomes a Camel route. This makes it the same from Apache Camel to manage and run these services, as they are just Camel routes. This means any tooling and API today that deals with Camel routes, also work with the REST services.
To use JMX with Camel then camel-management JAR must be included in the classpath.
This means you can use JMX to stop/start routes, and also get the JMX metrics about the routes, such as the number of messages processed, and their performance statistics.
There is also a REST Registry JMX MBean that contains a registry of all REST services that has been defined.
3.3.5. Inline REST DSL as a single route Copy linkLink copied to clipboard!
Camel 4.4 or older has inline-routes disabled by default. Camel 4.5 or newer has inline-routes enabled by default.
Each of the rest services becomes a Camel route, and this means, that if the rest service is calling another Camel route via direct, which is a widespread practice. This means that each rest service then becomes two routes. This can become harder to manage if you have many rest services.
When you use direct endpoints then you can enable REST DSL to automatically inline the direct route in the rest route, meaning that there is only one route per rest service.
When using inline-routes, then each REST endpoint should link 1:1 to a unique direct endpoint. The linked direct routes are inlined and therefore does not exists as independent routes, and they cannot be called from other regular Camel routes. In other words the inlined routes are essentially moved inside the rest-dsl and does not exist as a route. See more detils further below.
To do this you MUST use direct endpoints, and each endpoint must be unique name per service. And the option inlineRoutes must be enabled.
For example, in the Java DSL below we have enabled inline routes and each rest service uses direct endpoints with unique names.
And in XML:
If you use Camel Main, Camel Spring Boot, Camel Quarkus or Camel JBang, you can also enable this in application.properties such as:
camel.rest.inline-routes = true
camel.rest.inline-routes = true
Notice the REST services above each use a unique 1:1 linked direct endpoint (direct:customerDetail, direct:customerOrders direct:customerNewOrder). This means that you cannot call these routes from another route such as the following would not function:
from("kafka:new-order")
.to("direct:customerNewOrder");
from("kafka:new-order")
.to("direct:customerNewOrder");
So if you desire to call common routes from both REST DSL and other regular Camel routes then keep these in separate routes as shown:
Notice how the common shared route is separated into the route direct:commonCustomerNewOrder. Which can be called from both REST DSL and regular Camel routes.
3.3.6. Disabling REST services Copy linkLink copied to clipboard!
While developing REST services using REST DSL, you may want to temporary disabled some REST endpoints, which you can do using disabled as shown in the following.
rest("/customers/")
.get("/{id}").to("direct:customerDetail")
.get("/{id}/orders").to("direct:customerOrders").disabled("{{ordersEnabled}}")
.post("/neworder").to("direct:customerNewOrder").disabled();
rest("/customers/")
.get("/{id}").to("direct:customerDetail")
.get("/{id}/orders").to("direct:customerOrders").disabled("{{ordersEnabled}}")
.post("/neworder").to("direct:customerNewOrder").disabled();
And in XML:
In this example the last two REST endpoints are configured with disabled. You can use Property Placeholder to let an external configuration determine if the REST endpoint is disabled or not. In this example the /customers/{id}/orders endpoint is disabled via a placeholder. The last REST endpoint is hardcoded to be disabled.
3.3.7. Binding to POJOs using Copy linkLink copied to clipboard!
The REST DSL supports automatic binding json/xml contents to/from POJOs using data formats. By default, the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages.
You may want to use binding if you develop POJOs that maps to your REST services request and response types. This allows you as a developer to work with the POJOs in Java code.
The binding modes are:
| Binding Mode | Description |
|---|---|
|
| Binding is turned off. This is the default option. |
|
|
Binding is enabled, and Camel is relaxed and supports JSON, XML or both if the necessary data formats are included in the classpath. Notice that if for example |
|
|
Binding to/from JSON is enabled, and requires a JSON capable data format on the classpath. By default, Camel will use |
|
|
Binding to/from XML is enabled, and requires |
|
| Binding to/from JSON and XML is enabled and requires both data formats to be on the classpath. |
When using camel-jaxb for XML bindings, then you can use the option mustBeJAXBElement to relax the output message body must be a class with JAXB annotations. You can use this in situations where the message body is already in XML format, and you want to use the message body as-is as the output type. If that is the case, then set the dataFormatProperty option mustBeJAXBElement to false value.
The binding from POJO to JSon/JAXB will only happen if the content-type header includes the word json or xml representatively. This allows you to specify a custom content-type if the message body should not attempt to be marshalled using the binding. For example, if the message body is a custom binary payload, and so on.
When automatic binding from POJO to JSON/JAXB takes place the existing content-type header will by default be replaced with either application/json or application/xml. To disable the default behavior and be able to produce JSON/JAXB responses with custom content-type headers (e.g. application/user.v2+json) you configure this in Java DSL as shown below:
restConfiguration().dataFormatProperty("contentTypeHeader", "false");
restConfiguration().dataFormatProperty("contentTypeHeader", "false");
To use binding you must include the necessary data formats on the classpath, such as camel-jaxb and/or camel-jackson. And then enable the binding mode. You can configure the binding mode globally on the rest configuration, and then override per rest service as well.
To enable binding, you configure this in Java DSL as shown below:
restConfiguration().component("netty-http").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);
restConfiguration().component("netty-http").host("localhost").port(portNum).bindingMode(RestBindingMode.auto);
And in XML DSL:
<restConfiguration bindingMode="auto" component="netty-http" port="8080"/>
<restConfiguration bindingMode="auto" component="netty-http" port="8080"/>
When binding is enabled, Camel will bind the incoming and outgoing messages automatic, accordingly to the content type of the message. If the message is JSON, then JSON binding happens; and so if the message is XML, then XML binding happens. The binding happens for incoming and reply messages. The table below summaries what binding occurs for incoming and reply messages.
| Message Body | Direction | Binding Mode | Message Body |
|---|---|---|---|
| XML | Incoming | auto,xml,json_xml | POJO |
| POJO | Outgoing | auto,xml, json_xml | XML |
| JSON | Incoming | auto,json,json_xml | POJO |
| POJO | Outgoing | auto,json,json_xml | JSON |
When using binding, you must also configure what POJO type to map to. This is mandatory for incoming messages, and optional for outgoing.
When using binding mode json, xml or json_xml then Camel will automatically set consumers and produces on the rest endpoint (according to the mode), if not already explicit configured. For example, with binding mode json and setting the outType as UserPojo then Camel will define this rest endpoint as producing application/json.
For example, to map from xml/json to a pojo class UserPojo you do this in Java DSL as shown below:
Notice we use type to define the incoming type. We can optionally define an outgoing type (which can be a good idea, to make it known from the DSL and also for tooling and JMX APIs to know both the incoming and outgoing types of the REST services). To define the outgoing type, we use outType as shown below:
And in XML DSL:
<rest path="/users/">
<post type="UserPojo" outType="CountryPojo">
<to uri="direct:newUser"/>
</post>
</rest>
<rest path="/users/">
<post type="UserPojo" outType="CountryPojo">
<to uri="direct:newUser"/>
</post>
</rest>
To specify input and/or output using an array, append [] to the end of the canonical class name as shown in the following Java DSL:
The UserPojo is just a plain pojo with getter/setter as shown:
The UserPojo only supports JSON, as XML requires using JAXB annotations, so we can add those annotations if we want to support XML also
By having the JAXB annotations, the POJO supports both JSON and XML bindings.
3.3.7.1. Camel Rest-DSL configurations Copy linkLink copied to clipboard!
The REST DSL supports the following options:
| Name | Description | Default | Type |
|---|---|---|---|
| apiComponent | Sets the name of the Camel component to use as the REST API (such as swagger or openapi) | String | |
| apiContextPath | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | String | |
| apiHost | To use a specific hostname for the API documentation (such as swagger or openapi) This can be used to override the generated host with this configured hostname | String | |
| apiProperties | Sets additional options on api level | Map | |
| apiVendorExtension |
Whether a vendor extension is enabled in the REST APIs. If enabled, then Camel will include additional information as a vendor extension (e.g., keys starting with | false | boolean |
| bindingMode | Sets the binding mode to be used by the REST consumer | RestBindingMode.off | RestBindingMode |
| clientRequestValidation | Whether to enable validation of the client request to check: 1) Content-Type header matches what the REST DSL consumes; returns HTTP Status 415 if validation error. 2) Accept header matches what the REST DSL produces; returns HTTP Status 406 if validation error. 3) Missing required data (query parameters, HTTP headers, body); returns HTTP Status 400 if validation error. 4) Parsing error of the message body (JSON, XML or Auto binding mode must be enabled); returns HTTP Status 400 if validation error. | false | boolean |
| clientResponseValidation | Whether to check what Camel is returning as response to the client: 1) Status-code and Content-Type matches REST DSL response messages. 2) Check whether expected headers is included according to the REST DSL repose message headers. 3) If the response body is JSon then check whether its valid JSon. Returns 500 if validation error detected. | false | boolean |
| component | Sets the name of the Camel component to use as the REST consumer | String | |
| componentProperties | Sets additional options on component level | Map | |
| consumerProperties | Sets additional options on consumer level | Map | |
| contextPath | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | String | |
| corsHeaders | Sets the CORS headers to use if CORS has been enabled. | Map | |
| dataFormatProperties | Sets additional options on data format level | Map | |
| enableCORS | To specify whether to enable CORS, which means Camel will automatically include CORS in the HTTP headers in the response. This option is default false | false | boolean |
| enableNoContentResponse | To specify whether to return HTTP 204 with an empty body when a response contains an empty JSON object or XML root object. | false | boolean |
| endpointProperties | Sets additional options on endpoint level | Map | |
| host | Sets the hostname to use by the REST consumer | String | |
| hostNameResolver | Sets the resolver to use for resolving hostname | RestHostNameResolver.allLocalIp | RestHostNameResolver |
| inlineRoutes | Inline routes in rest-dsl which are linked using direct endpoints. By default, each service in REST DSL is an individual route, meaning that you would have at least two routes per service (rest-dsl, and the route linked from rest-dsl). Enabling this allows Camel to optimize and inline this as a single route. However, this requires using direct endpoints, which must be unique per service. This option is default false. | false | boolean |
| jsonDataFormat | Sets a custom JSON data format to be used Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | String | |
| port | Sets the port to use by the REST consumer | int | |
| producerApiDoc | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-openapi-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | String | |
| producerComponent | Sets the name of the Camel component to use as the REST producer | String | |
| scheme | Sets the scheme to use by the REST consumer | String | |
| skipBindingOnErrorCode | Whether to skip binding output if there is a custom HTTP error code, and instead use the response body as-is. This option is default true. | true | boolean |
| useXForwardHeaders | Whether to use X-Forward headers to set host , and so on. for Swagger. This option is default true. | true | boolean |
| xmlDataFormat | Sets a custom XML data format to be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | String |
For example, to configure to use the jetty component on port 9091, then we can do as follows:
restConfiguration().component("jetty").port(9091).componentProperty("foo", "123");
restConfiguration().component("jetty").port(9091).componentProperty("foo", "123");
And with XML DSL:
<restConfiguration component="jetty" port="9091"> <componentProperty key="foo" value="123"/> </restConfiguration>
<restConfiguration component="jetty" port="9091">
<componentProperty key="foo" value="123"/>
</restConfiguration>
If no component has been explicitly configured, then Camel will look up if there is a Camel component that integrates with the REST DSL, or if a org.apache.camel.spi.RestConsumerFactory is registered in the registry. If either one is found, then that is being used.
You can configure properties on these levels.
- component - Is used to set any options on the Component class. You can also configure these directly on the component.
- endpoint - Is used set any option on the endpoint level. Many of the Camel components has many options you can set on endpoint level.
- consumer - Is used to set any option on the consumer level.
- data format - Is used to set any option on the data formats. For example, to enable pretty print in the JSON data format.
- cors headers - If cors is enabled, then custom CORS headers can be set. See below for the default values which are in used. If a custom header is set then that value takes precedence over the default value.
You can set multiple options of the same level, so you can, for example, configure two component options, and three endpoint options, and so on.
3.3.8. Enabling or disabling Jackson JSON features Copy linkLink copied to clipboard!
When using JSON binding, you may want to turn specific Jackson features on or off. For example, to disable failing on unknown properties (e.g., JSON input has a property which cannot be mapped to a POJO) then configure this using the dataFormatProperty as shown below:
restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json)
.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES");
restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json)
.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES");
You can disable more features by separating the values using comma, such as:
.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE");
.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE");
Likewise, you can enable features using the enableFeatures such as:
restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json)
.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE")
.dataFormatProperty("json.in.enableFeatures", "FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS");
restConfiguration().component("jetty").host("localhost").port(getPort()).bindingMode(RestBindingMode.json)
.dataFormatProperty("json.in.disableFeatures", "FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE")
.dataFormatProperty("json.in.enableFeatures", "FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS");
The values that can be used for enabling and disabling features on Jackson are the names of the enums from the following three Jackson classes
-
com.fasterxml.jackson.databind.SerializationFeature -
com.fasterxml.jackson.databind.DeserializationFeature -
com.fasterxml.jackson.databind.MapperFeature
The rest configuration is, of course, also possible using XML DSL:
<restConfiguration component="jetty" host="localhost" port="9090" bindingMode="json"> <dataFormatProperty key="json.in.disableFeatures" value="FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE"/> <dataFormatProperty key="json.in.enableFeatures" value="FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS"/> </restConfiguration>
<restConfiguration component="jetty" host="localhost" port="9090" bindingMode="json">
<dataFormatProperty key="json.in.disableFeatures" value="FAIL_ON_UNKNOWN_PROPERTIES,ADJUST_DATES_TO_CONTEXT_TIME_ZONE"/>
<dataFormatProperty key="json.in.enableFeatures" value="FAIL_ON_NUMBERS_FOR_ENUMS,USE_BIG_DECIMAL_FOR_FLOATS"/>
</restConfiguration>
3.3.9. Default CORS headers Copy linkLink copied to clipboard!
If CORS is enabled, then the "follow headers" is in use by default. You can configure custom CORS headers that take precedence over the default value.
| Key | Value |
|---|---|
|
| * |
|
| GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH |
|
| Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers |
|
| 3600 |
3.3.10. Defining a custom error message as-is Copy linkLink copied to clipboard!
If you want to define custom error messages to be sent back to the client with a HTTP error code (e.g., such as 400, 404 , and so on.) then you set a header with the key Exchange.HTTP_RESPONSE_CODE to the error code (must be 300+) such as 404. And then the message body with any reply message, and optionally set the content-type header as well. There is a little example shown below:
In this example, if the input id is a number that is below 100, we want to send back a custom error message, using the UserErrorService bean, which is implemented as shown:
In the UserErrorService bean, we build our custom error message, and set the HTTP error code to 400. This is important, as that tells rest-dsl that this is a custom error message, and the message should not use the output pojo binding (e.g., would otherwise bind to CountryPojo).
3.3.10.1. Catching JsonParserException and returning a custom error message Copy linkLink copied to clipboard!
You can return a custom message as-is (see previous section). So we can leverage this with Camel error handler to catch JsonParserException, handle that exception and build our custom response message. For example, to return a HTTP error code 400 with a hardcoded message, we can do as shown below:
onException(JsonParseException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
.setBody().constant("Invalid json data");
onException(JsonParseException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.setHeader(Exchange.CONTENT_TYPE, constant("text/plain"))
.setBody().constant("Invalid json data");
3.3.11. Query/Header Parameter default Values Copy linkLink copied to clipboard!
You can specify default values for parameters in the rest-dsl, such as the verbose parameter below:
The default value is automatic set as header on the incoming Camel Message. So if the call to /customers/id/orders do not include a query parameter with key verbose then Camel will now include a header with key verbose and the value false because it was declared as the default value. This functionality is only applicable for query parameters. Request headers may also be defaulted in the same way.
3.3.12. Client Request and Response Validation Copy linkLink copied to clipboard!
It is possible to enable validation of the incoming client request. The validation checks for the following:
- Content-Type header matches what the REST DSL consumes. (Returns HTTP Status 415)
- Accept header matches what the REST DSL produces. (Returns HTTP Status 406)
- Missing required data (query parameters, HTTP headers, body). (Returns HTTP Status 400)
- Checking if query parameters or HTTP headers has not-allowed values. (Returns HTTP Status 400)
- Parsing error of the message body (JSON, XML or Auto binding mode must be enabled). (Returns HTTP Status 400)
If the validation fails, then REST DSL will return a response with an HTTP error code.
The validation is by default turned off (to be backwards compatible). It can be turned on via clientRequestValidation as shown below:
restConfiguration().component("jetty").host("localhost")
.clientRequestValidation(true);
restConfiguration().component("jetty").host("localhost")
.clientRequestValidation(true);
The validator is pluggable and Camel provides a default implementation out of the box. However, the camel-openapi-validator uses the third party Atlassian Swagger Request Validator library instead for client request validator. This library is a more extensive validator than the default validator from camel-core, such as being able to validate the payload is structured according to the OpenAPI specification.
In Camel 4.13 we added a response validator as well which is intended more as development assistance that you can enable while building your Camel integrations, and help ensure what Camel is sending back to the HTTP client is valid. The response validator checks for the following:
- Status-code and Content-Type matches REST DSL response messages.
- Check whether expected headers is included according to the REST DSL repose message headers.
- If the response body is JSon then check whether its valid JSon.
If any error is detected the HTTP Status 500 is returned.
Also, the camel-openapi-validator can be added to the classpath to have a more powerful response validator, that can be used to validate the response payload is structured according to the OpenAPI specification.
3.3.13. OpenAPI / Swagger API Copy linkLink copied to clipboard!
The REST DSL supports OpenAPI and Swagger by the camel-openapi-java modules.
You can define each parameter fine-grained with details such as name, description, data type, parameter type and so on, using the param. For example, to define the id path parameter, you can do as shown below:
And in Java DSL
.get("/{id}").description("Find user by id").outType(User.class)
.param().name("id").type(path).description("The id of the user to get").dataType("int").endParam()
.to("bean:userService?method=getUser(${header.id})")
.get("/{id}").description("Find user by id").outType(User.class)
.param().name("id").type(path).description("The id of the user to get").dataType("int").endParam()
.to("bean:userService?method=getUser(${header.id})")
The body parameter type requires to use body as well for the name. For example, a REST PUT operation to create/update an user could be done as:
And in Java DSL:
.put().description("Updates or create a user").type(User.class)
.param().name("body").type(body).description("The user to update or create").endParam()
.to("bean:userService?method=updateUser")
.put().description("Updates or create a user").type(User.class)
.param().name("body").type(body).description("The user to update or create").endParam()
.to("bean:userService?method=updateUser")
3.3.13.1. Vendor Extensions Copy linkLink copied to clipboard!
The generated API documentation can be configured to include vendor extensions (https://swagger.io/specification/#specificationExtensions) which document the operations and definitions with additional information, such as class name of model classes, camel context id and route id’s. This information can be very helpful for developers, especially during troubleshooting. However, at production usage you may wish to not have this turned on to avoid leaking implementation details into your API docs.
The vendor extension information is stored in the API documentation with keys starting with x-.
Not all third party API gateways and tools support vendor-extensions when importing your API docs.
The vendor extensions can be turned on RestConfiguration via the apiVendorExtension option:
And in XML DSL:
3.3.13.2. Supported API properties Copy linkLink copied to clipboard!
The following table lists supported API properties and explains their effect. To set them use apiProperty(String, String) in the Java DSL or <apiProperty> when defining the REST API via XML configuration. Properties in bold are required by the OpenAPI 2.0 specification. Most of the properties affect the OpenAPI Info object, License object or Contact object.
| Property | Description |
| api.version | Version of the API |
| api.title | Title of the API |
| api.description | Description of the API |
| api.termsOfService | API Terms of Service of the API |
| api.license.name | License information of the API |
| api.license.url | URL for the License of the API |
| api.contact.name | The identifying name of the contact person/organization |
| api.contact.url | The URL pointing to the contact information |
| api.contact.email | The email address of the contact person/organization |
| api.specification.contentType.json |
The Content-Type of the served OpenAPI JSON specification, |
| api.specification.contentType.yaml |
The Content-Type of the served OpenAPI YAML specification, |
| externalDocs.url | The URI for the target documentation. This must be in the form of a URI |
| externalDocs.description | A description of the target documentation |
3.4. REST DSL with OpenAPI contract first Copy linkLink copied to clipboard!
This section describes a contract-first approach to working with REST DSL, using a vanilla OpenAPI specification.
For the legacy code-first approach, see the section REST DSL with OpenAPI code first
From Camel 4.6 onwards, the REST DSL has been improved with a contract-first approach using vanilla OpenAPI specification.
3.4.1. How it works Copy linkLink copied to clipboard!
The REST DSL OpenAPI is a facade that builds REST OpenAPI endpoint as consumer for Camel routes. The actual HTTP transport is leveraged by using the Platform HTTP, which makes it plugin to Camel Spring Boot, Camel Quarkus or can run standalone with Camel Main.
3.4.1.1. Limitations Copy linkLink copied to clipboard!
Camel does not support websockets from the OpenAPI 3.1 specification. Neither is (at this time of writing) any security aspects from the OpenAPI specification in use.
3.4.2. Contract first Copy linkLink copied to clipboard!
The contract-first approach requires you to have an existing OpenAPI v3 specification file. This contract is a standard OpenAPI contract, and you can use any existing API design tool to build such contracts.
Camel support OpenAPI v3.0 and v3.1.
In Camel, you then use the REST DSL in contract-first mode. For example, having a contract in a file named my-contract.json, you can then copy this file to src/main/resources so it’s loaded from classpath.
In Camel REST DSL you can then very easily define contract-first as shown below:
- Java
@Override public void configure() throws Exception { rest().openApi("petstore-v3.json"); }@Override public void configure() throws Exception { rest().openApi("petstore-v3.json"); }Copy to Clipboard Copied! Toggle word wrap Toggle overflow - XML
<rest> <openApi specification="petstore-v3.json"/> </rest>
<rest> <openApi specification="petstore-v3.json"/> </rest>Copy to Clipboard Copied! Toggle word wrap Toggle overflow - YAML
- rest: openApi: specification: petstore-v3.json- rest: openApi: specification: petstore-v3.jsonCopy to Clipboard Copied! Toggle word wrap Toggle overflow
When Camel starts, the OpenAPI specification file is loaded and parsed. For every API, Camel builds HTTP REST endpoint, which are routed 1:1 to Camel routes using the direct:operationId naming convention.
The pestore has 18 APIs here we look at the 5 user APIs:
http://0.0.0.0:8080/api/v3/user (POST) (accept:application/json,application/x-www-form-urlencoded,application/xml produce:application/json,application/xml)
http://0.0.0.0:8080/api/v3/user/createWithList (POST) (accept:application/json produce:application/json,application/xml)
http://0.0.0.0:8080/api/v3/user/login (GET) (produce:application/json,application/xml)
http://0.0.0.0:8080/api/v3/user/logout (GET)
http://0.0.0.0:8080/api/v3/user/{username} (DELETE,GET,PUT)
http://0.0.0.0:8080/api/v3/user (POST) (accept:application/json,application/x-www-form-urlencoded,application/xml produce:application/json,application/xml)
http://0.0.0.0:8080/api/v3/user/createWithList (POST) (accept:application/json produce:application/json,application/xml)
http://0.0.0.0:8080/api/v3/user/login (GET) (produce:application/json,application/xml)
http://0.0.0.0:8080/api/v3/user/logout (GET)
http://0.0.0.0:8080/api/v3/user/{username} (DELETE,GET,PUT)
These APIs are outputted using the URI that clients can use to call the service. Each of these APIs has a unique operation id which is what Camel uses for calling the route. This gives:
http://0.0.0.0:8080/api/v3/user direct:createUser
http://0.0.0.0:8080/api/v3/user/createWithList direct:createUsersWithListInput
http://0.0.0.0:8080/api/v3/user/login direct:loginUser
http://0.0.0.0:8080/api/v3/user/logout direct:logoutUser
http://0.0.0.0:8080/api/v3/user/{username} direct:getUserByName
http://0.0.0.0:8080/api/v3/user direct:createUser
http://0.0.0.0:8080/api/v3/user/createWithList direct:createUsersWithListInput
http://0.0.0.0:8080/api/v3/user/login direct:loginUser
http://0.0.0.0:8080/api/v3/user/logout direct:logoutUser
http://0.0.0.0:8080/api/v3/user/{username} direct:getUserByName
You should then implement a route for each API that starts from those direct endpoints listed above, such as:
- Java
Copy to Clipboard Copied! Toggle word wrap Toggle overflow - XML
Copy to Clipboard Copied! Toggle word wrap Toggle overflow - YAML
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.4.2.1. Configuring Base Path Copy linkLink copied to clipboard!
By default, Camel uses the base path specified in the OpenAPI contract such as:
"basePath": {
"default": "/api/v3"
}
"basePath": {
"default": "/api/v3"
}
You can configure Camel to use a different base path (such as cheese) by either setting the base-path on the REST OpenAPI component in application.properties, or configure it in the rest configuration YAML:
- Properties
camel.component.rest-openapi.base-path = /cheese
camel.component.rest-openapi.base-path = /cheeseCopy to Clipboard Copied! Toggle word wrap Toggle overflow - YAML
Copy to Clipboard Copied! Toggle word wrap Toggle overflow
3.4.2.2. Ignoring missing API operations Copy linkLink copied to clipboard!
When using OpenAPI with contract-first, then Camel will on startup check if there is a corresponding direct:operationId route for every API service. If some operations are missing, then Camel will fail on startup with an error.
During development, you can use missingOperation to ignore this as shown:
rest().openApi("petstore-v3.json").missingOperation("ignore");
rest().openApi("petstore-v3.json").missingOperation("ignore");
This allows you to implement the APIs one by one over time.
3.4.2.3. Mocking API operations Copy linkLink copied to clipboard!
This is similar to ignoring missing API operations, as you can tell Camel to mock instead, as shown:
rest().openApi("petstore-v3.json").missingOperation("mock");
rest().openApi("petstore-v3.json").missingOperation("mock");
When using mock, then Camel will (for missing operations) simulate a successful response:
- attempting to load canned responses from the file system.
-
for GET verbs then attempt to use example inlined in the OpenAPI
responsesection. - for other verbs (DELETE, PUT, POST, PATCH) then return the input body as response.
- if none of the above, then return empty body.
This allows you to have a set of files that you can use for development and testing purposes.
The files should be stored in camel-mock when using Camel JBang, and src/main/resources/camel-mock for Maven/Gradle based projects.
For example, the following Camel JBang example is structured as:
README.md camel-mock/pet/123.json petstore-v3.json petstore.camel.yaml
README.md
camel-mock/pet/123.json
petstore-v3.json
petstore.camel.yaml
And the Camel route:
When running this example, you can call the APIs and have an empty successful response. However, for the url pet/123 the file camel-mock/pet/123.json will be loaded as the response as shown below:
curl http://0.0.0.0:8080/api/v3/pet/123
{
"pet": "donald the dock"
}
$ curl http://0.0.0.0:8080/api/v3/pet/123
{
"pet": "donald the dock"
}
If no file is found, then Camel will attempt to find an example from the response section in the OpenAPI specification.
In the response section below, then for success GET response (200) then for the application/json content-type, we have an inlined example. Note if there are multiple examples for the same content-type, then Camel will pick the first example, so make sure it’s the best example you want to let Camel use as mocked response body.
3.4.2.4. Binding to POJO classes Copy linkLink copied to clipboard!
contract-first REST DSL with OpenAPI also supports binding mode to JSON and XML. This works the same as code first REST DSL.
However, we have added the bindingPackageScan configuration to make it possible for Camel to automatically discover POJO classes from classpath.
When using Spring Boot or Quarkus, then you must configure the package names (base) in Java or in application.properties:
- Java
// turn on json binding and scan for POJO classes in the model package restConfiguration().bindingMode(RestBindingMode.json) .bindingPackageScan("sample.petstore.model");// turn on json binding and scan for POJO classes in the model package restConfiguration().bindingMode(RestBindingMode.json) .bindingPackageScan("sample.petstore.model");Copy to Clipboard Copied! Toggle word wrap Toggle overflow - Properties
camel.rest.bindingMode = json camel.rest.bindingPackageScan = sample.petstore.model
camel.rest.bindingMode = json camel.rest.bindingPackageScan = sample.petstore.modelCopy to Clipboard Copied! Toggle word wrap Toggle overflow
Then Camel will automatically for every OpenAPI operation detect the specified schemas for incoming and outgoing responses, and map that to Java POJO classes by class name.
For example, the getPetById operation in the OpenAPI contract:
Here Camel will detect the schema part:
"schema": {
"$ref": "#/components/schemas/Pet"
}
"schema": {
"$ref": "#/components/schemas/Pet"
}
And compute the class name as Pet and attempt to discover this class from classpath scanning specified via the bindingPackageScan option.
You can also use title attribute of the Schema to provide the name of the POJO class. This is helpful when you need to use one name for the Schema in the OpenAPI contract and use another name for the actual POJO class in the implementation.
Here Camel will detect the class name as PetResponseDto and try to discover it from the classpath. This can be used for both Responses and RequestBodies.
You can source code generate Java POJO classes from an OpenAPI specification via tooling such as the swagger-codegen-maven-plugin Maven plugin. For more details, see this Spring Boot example.
3.4.2.5. Expose API specification Copy linkLink copied to clipboard!
The OpenAPI specification is by default not exposed on the HTTP endpoint. You can make this happen by setting the rest-configuration as follows:
- restConfiguration:
apiContextPath: /api-doc
- restConfiguration:
apiContextPath: /api-doc
Then the specification is accessible on /api-doc on the embedded HTTP server, so typically that would be http://localhost:8080/api-doc.
In the returned API specification the server section has been modified to return the IP of the current server. This can be controlled via:
- restConfiguration:
apiContextPath: /api-doc
hostNameResolver: localIp
- restConfiguration:
apiContextPath: /api-doc
hostNameResolver: localIp
And you can turn this off by setting the value to none so the server part is taken verbatim from the specification file.
- restConfiguration:
apiContextPath: /api-doc
hostNameResolver: none
- restConfiguration:
apiContextPath: /api-doc
hostNameResolver: none
3.4.3. Examples Copy linkLink copied to clipboard!
You can find a few examples such as: