# REST DSL with contract-first OpenAPI

From **Camel 4.6** onwards, the [Rest DSL](rest-dsl.md) has been improved with a _contract-first_ approach using vanilla OpenAPI specification.

## How it works

The Rest DSL OpenAPI is a facade that builds [Rest OpenAPI](../components/4.22.x/rest-openapi-component.md) endpoint as consumer for Camel routes. The actual HTTP transport is leveraged by using the [Platform HTTP](../components/4.22.x/platform-http-component.md), which makes it plugin to Camel Spring Boot, Camel Quarkus or can run standalone with Camel Main.

### Limitations

Camel does not support websockets from the OpenAPI 3.1 specification. OpenAPI security schemes and operation security requirements are not interpreted from the specification; configure any Camel endpoint security explicitly.

### OAuth Bearer token validation

OpenAPI `securitySchemes` are not mapped automatically to Camel endpoint security options. To validate incoming `Authorization: Bearer` tokens, pass the `oauthProfile` endpoint option to the HTTP consumer component selected by Rest DSL.

-   Java
    
-   XML
    
-   YAML
    

```java
restConfiguration()
    .endpointProperty("oauthProfile", "myprofile");

rest().openApi("petstore-v3.json");
```

```xml
<restConfiguration>
  <endpointProperty key="oauthProfile" value="myprofile"/>
</restConfiguration>

<rest>
  <openApi specification="petstore-v3.json"/>
</rest>
```

```yaml
- restConfiguration:
    endpointProperty:
      - key: oauthProfile
        value: myprofile
- rest:
    openApi:
      specification: petstore-v3.json
```

The built-in Rest OpenAPI consumer uses [platform-http](../components/4.22.x/platform-http-component.md), which supports the `oauthProfile` option. Custom `RestOpenApiConsumerFactory` delegates can also receive the endpoint property if they support it. Direct `rest-openapi` consumer endpoint URIs can also pass the option to the delegate, for example `rest-openapi:petstore-v3.json?consumerComponentName=platform-http&oauthProfile=myprofile`. Consumer endpoint URIs identify the OpenAPI specification and do not include an `#operationId` fragment. The `oauthProfile` option is forwarded to the selected delegate, which is responsible for enforcing it. The route fails at startup when the resolved `RestOpenApiConsumerFactory` does not declare that its consumers enforce `oauthProfile`, so a misconfigured delegate cannot start without the expected protection.

## Contract first

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.

> **Tip**
> 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
    
-   XML
    
-   YAML
    

```java
@Override
public void configure() throws Exception {
    rest().openApi("petstore-v3.json");
}
```

```xml
<rest>
  <openApi specification="petstore-v3.json"/>
</rest>
```

```yaml
- rest:
    openApi:
      specification: petstore-v3.json
```

When Camel startup 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:

```text
 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:

```text
 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
    
-   XML
    
-   YAML
    

```java
@Override
public void configure() throws Exception {
    rest().openApi("petstore-v3.json");

    from("direct:getUserByName")
       ... // do something here
}
```

```xml
<rest>
  <openApi specification="petstore-v3.json"/>
</rest>
<route>
  <from uri="direct:getUserByName"/>
  <!-- do something here -->
</route>
```

```yaml
- rest:
    openApi:
      specification: petstore-v3.json
- route:
    from:
      uri: direct:getUserByName
      steps:
        - log:
            message: "do something here"
```

### Configuring Base Path

By default, Camel uses the base path that are specified in the OpenAPI contract such as:

```json
    "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 as follows, such as in `application.properties`:

```properties
camel.component.rest-openapi.base-path = /cheese
```

Or configure this in the _rest configuration_ such as:

-   Java
    
-   XML
    
-   YAML
    

```java
restConfiguration().contextPath("/cheese").clientRequestValidation(true);

rest().openApi().specification("petstore-v3.json");
```

```xml
<restConfiguration contextPath="/cheese" clientRequestValidation="true"/>

<rest>
  <openApi specification="petstore-v3.json"/>
</rest>
```

```yaml
- restConfiguration:
    clientRequestValidation: true
    contextPath: /cheese
- rest:
    openApi:
      specification: petstore-v3.json
```

### Ignoring missing API operations

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:

-   Java
    
-   XML
    
-   YAML
    

```java
    rest().openApi().specification("petstore-v3.json").missingOperation("ignore");
```

```xml
<rest>
  <openApi specification="petstore-v3.json" missingOperation="ignore"/>
</rest>
```

```yaml
- rest:
    openApi:
      specification: petstore-v3.json
      missingOperation: ignore
```

This allows you to implement the APIs one by one over time.

### Handling unmatched requests

By default, requests that do not match any operation in the OpenAPI specification are answered by the HTTP layer of the runtime with HTTP `404` (unknown path) or `405` with an `Allow` header.

Set `unmatchedRequestHandling` to `camel` to instead route such requests to Camel, where they are answered by an unmatched request handler (see the [rest-openapi](../components/4.22.x/rest-openapi-component.md) component documentation for how to plug in a `RestUnmatchedRequestHandler` that controls the response body):

-   Java
    
-   XML
    
-   YAML
    

```java
    rest().openApi()
        .specification("petstore-v3.json")
        .missingOperation("ignore")
        .unmatchedRequestHandling("camel");
```

```xml
<rest>
  <openApi specification="petstore-v3.json" missingOperation="ignore" unmatchedRequestHandling="camel"/>
</rest>
```

```yaml
- rest:
    openApi:
      specification: petstore-v3.json
      missingOperation: ignore
      unmatchedRequestHandling: camel
```

### Mocking API operations

This is similar to ignoring missing API operations, as you can tell Camel to mock instead, as shown:

-   Java
    
-   XML
    
-   YAML
    

```java
    rest().openApi().specification("petstore-v3.json").missingOperation("mock");
```

```xml
<rest>
  <openApi specification="petstore-v3.json" missingOperation="mock"/>
</rest>
```

```yaml
- rest:
    openApi:
      specification: petstore-v3.json
      missingOperation: mock
```

When using _mock_, then Camel will (for missing operations) simulate a successful response:

1.  attempting to load canned responses from the file system.
    
2.  for GET verbs then attempt to use example inlined in the OpenAPI `response` section.
    
3.  for other verbs (DELETE, PUT, POST, PATCH) then return the input body as response.
    
4.  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 CLI, and `src/main/resources/camel-mock` for Maven/Gradle based projects.

For example, the following [Camel CLI example](https://github.com/apache/camel-kamelets-examples/tree/main/jbang/open-api-contract-first) is structured as:

```text
README.md
camel-mock/pet/123.json
petstore-v3.json
petstore.camel.yaml
```

And the Camel route:

-   Java
    
-   XML
    
-   YAML
    

```java
restConfiguration().clientRequestValidation(true);

rest().openApi().specification("petstore-v3.json").missingOperation("mock");
```

```xml
<restConfiguration clientRequestValidation="true"/>

<rest>
  <openApi specification="petstore-v3.json" missingOperation="mock"/>
</rest>
```

```yaml
- restConfiguration:
    clientRequestValidation: true
- rest:
    openApi:
      missingOperation: mock
      specification: petstore-v3.json
```

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:

```bash
$ 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.

```json
"responses": {
    "200": {
        "description": "successful operation",
        "content": {
            "application/xml": {
                "schema": {
                    "$ref": "#/components/schemas/Pet"
                }
            },
            "application/json": {
                "schema": {
                    "$ref": "#/components/schemas/Pet"
                },
                "examples": {
                    "success": {
                        "summary": "A cat",
                        "value": "{\"pet\": \"Jack the cat\"}"
                    }
                }
            }
        }
    },
    "400": {
        "description": "Invalid ID supplied"
    },
    "404": {
        "description": "Pet not found"
    }
```

### Binding to POJO classes

_contract-first_ Rest DSL with OpenAPI also supports binding mode to JSON and XML. This works the same as _code first_ [Rest DSL](rest-dsl.md).

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) such as follows:

-   Java
    
-   XML
    
-   YAML
    
-   Application Properties
    

```java
// turn on json binding and scan for POJO classes in the model package
restConfiguration().bindingMode(RestBindingMode.json)
        .bindingPackageScan("sample.petstore.model");
```

```xml
<restConfiguration bindingMode="json" bindingPackageScan="sample.petstore.model"/>
```

```yaml
- restConfiguration:
    bindingMode: json
    bindingPackageScan: sample.petstore.model
```

You can also configure this in `application.properties`:

```properties
camel.rest.bindingMode = json
camel.rest.bindingPackageScan = sample.petstore.model
```

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:

```json
"responses": {
    "200": {
        "description": "successful operation",
        "content": {
            "application/xml": {
                "schema": {
                    "$ref": "#/components/schemas/Pet"
                }
            },
            "application/json": {
                "schema": {
                    "$ref": "#/components/schemas/Pet"
                }
            }
        }
    },
```

Here Camel will detect the `schema` part:

```json
"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.

```json
"components": {
        "schemas": {
            "Pet": {
                "type": "object",
                "title": "PetResponseDto",
                "properties": {
                    ...
                }
            }
        }
    },
```

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](https://github.com/apache/camel-spring-boot-examples/tree/main/openapi-contract-first).

### Expose API specification

The OpenAPI specification is by default not exposed on the HTTP endpoint. You can make this happen by setting the rest-configuration as follows:

-   Java
    
-   XML
    
-   YAML
    

```java
restConfiguration().apiContextPath("/api-doc");
```

```xml
<restConfiguration apiContextPath="/api-doc"/>
```

```yaml
- 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](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:

-   Java
    
-   XML
    
-   YAML
    

```java
restConfiguration().apiContextPath("/api-doc").hostNameResolver(RestHostNameResolver.localIp);
```

```xml
<restConfiguration apiContextPath="/api-doc" hostNameResolver="localIp"/>
```

```yaml
- 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.

-   Java
    
-   XML
    
-   YAML
    

```java
restConfiguration().apiContextPath("/api-doc").hostNameResolver(RestHostNameResolver.none);
```

```xml
<restConfiguration apiContextPath="/api-doc" hostNameResolver="none"/>
```

```yaml
- restConfiguration:
    apiContextPath: /api-doc
    hostNameResolver: none
```

### Restricting external references

A contract can reference other documents with `$ref`: files on the classpath or the file system, and documents on an http(s) server. Camel loads every such document when the route starts. The `externalReferences` option restricts this: `all` (default) allows any reference, `local` allows references to the classpath and the file system only, and `none` allows only references inside the contract. The check follows the references into the local documents it allows, and a document it cannot read, or a fragment of it that it cannot find, fails the start too. A reference the option does not allow fails the start, with a message that names it.

-   Java
    
-   XML
    
-   YAML
    

```java
    rest().openApi().specification("petstore-v3.json").externalReferences("none");
```

```xml
<rest>
  <openApi specification="petstore-v3.json" externalReferences="none"/>
</rest>
```

```yaml
- rest:
    openApi:
      specification: petstore-v3.json
      externalReferences: none
```

The option can also be set once on the `rest-openapi` component, for example with `camel.component.rest-openapi.external-references=none`, which covers every contract and the specification served as api-doc. See the [REST OpenAPI component](../components/4.22.x/rest-openapi-component.md) for the details.

## Examples

You can find a few examples such as:

-   [Spring Boot OpenAPI Contract First](https://github.com/apache/camel-spring-boot-examples/tree/main/openapi-contract-first)
    
-   [JBang OpenAPI](https://github.com/apache/camel-jbang-examples/tree/main/openapi)
    
-   [JBang OpenAPI (Old Example)](https://github.com/apache/camel-kamelets-examples/tree/main/jbang/open-api-contract-first)