Contract-First means what the name implies that we write the contract between client and server first and implement the code for it after. This is a good way to break up the task of creating an API in smaller parts which can be handled over multiple professions. For example, the OpenAPI specification can be created by an IT-architect and the implementation can be done by a programmer, and lastly the API documentation can be carried out by an communications expert.
In this article I’m going to build a simple OpenAPI implementation in Apache Camel and it’s rest-openapi component in a SpringBoot application.
1. We start with the API Specification:
11 | description: Default response |
23 | description: Default response |
A few things to note here:
/test – this is the url that the client will use
operationId for the test endpoint – is the route that will receive the call from url above
/user/{userId} – url with parameter that the client will use
operationId – here the operationId does not match the url, which is fine. The call will go to the route direct:getUser with the userId in a header on the message seen below
2. Implementation of the Camel solution
01 | package com.example.contract_first_example; |
04 | import org.apache.camel.builder.RouteBuilder; |
05 | import org.springframework.stereotype.Component; |
09 | * A Camel Java DSL Router for Contract First Example |
12 | public class MyApp extends RouteBuilder { |
14 | public void configure() throws Exception { |
15 | rest().openApi().specification( "hello-rest-service.yaml" ); |
18 | .setBody().constant( "Hello from Camel!" ); |
21 | .process(exchange -> { |
22 | exchange.getMessage().setBody( "Hello from user: " |
23 | + exchange.getMessage().getHeader( "userId" )); |
3. Now the implementation is done and we move on to testing:
1 | PS C:\Users\niklas> curl -XGET localhost:8080/hello |
3 | PS C:\Users\niklas> curl -XGET localhost:8080/user/11 |
And that is all there is – pretty simple, like most things in the Camel world 
Tested on Java 17, OpenAPI 3.0, Apache Camel 4.9.0 and SpringBoot 3.3.4 in a Windows 10 environment