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:
openapi: 3.0.3 info: title: Basic API version: "1.0" paths: /test: get: operationId: test responses: 200: description: Default response /user/{userId}: get: operationId: getUser parameters: - name: userId in: path required: true schema: type: string responses: 200: 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
package com.example.contract_first_example; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; /** * A Camel Java DSL Router for Contract First Example */ @Component public class MyApp extends RouteBuilder { @Override public void configure() throws Exception { rest().openApi().specification("hello-rest-service.yaml"); from("direct://hello") .setBody().constant("Hello from Camel!"); from("direct://getUser") .process(exchange -> { exchange.getMessage().setBody("Hello from user: " + exchange.getMessage().getHeader("userId")); }); } }
3. Now the implementation is done and we move on to testing:
PS C:\Users\niklas> curl -XGET localhost:8080/hello Hello from Camel! PS C:\Users\niklas> curl -XGET localhost:8080/user/11 Hello from 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
0 Comments.