Harsh Techie working for a fintech startup in Amsterdam.

Contract First Development - Building REST service using Swagger & Spring Boot

Contract First Development - Building REST service using Swagger & Spring Boot

One of the latest trends in software development is to have a well defined contract for the REST APIs before building any concrete service around it. Whether it’s a public facing API or an internally consumable API, having a well defined contract is imperative.

In this post, we will take a step by step approach on building a skeleton(contract) for our REST APIs and then put some flesh on the bones using Spring Boot. For our learning purpose we will take a simple example of a stocks application that has basic CRUD operations around a stock resource.

Defining the Contract

It’s always handy to settle on a contract first with our probable API consumers in case of an internal API, as it’s quite tedious to change the contract later on after the service is built.

We would begin with defining a swagger specification of our APIs taking full advantage of OpenAPI Specification. I personally like using yaml to define API contracts but you can always use json as well.

The above contract nicely describes the possible REST methods and their corresponding request & response models. We would now take this contract and build our service around this.

Generating API interface from the contract

Moving on let us now put some flesh on the bones that we just crafted.

Add the following dependency to your project’s pom.xml


Next configure swagger-codegen-plugin to generate the API for you.

Run the following command to verify.

mvn clean generate-resources

Check your target directory to see all your generated models and StocksAPI interface. The generated code should like this :

Define your controller

The generated StocksAPI.java interface could now be extended to define our controller.

In our next post we will talk about how to consume a swagger API contract.

Buy Me A Coffee

comments powered by Disqus