Skip to main content

API first approach with Swagger v3/OpenAPI Specs & Spring Boot

API first approach has a ton of advantage's, it helps developers and functional analysts to visualize the APIs before developers start implementing it. It also helps the UI developers and the testers to start working on their tasks parallelly while developers are busy implementing.

In this blog I will explain how to create such API contracts with Swagger 3.0 on OpenAPI specifications (OAS) and using Maven, how can we easily generate Spring Boot code for such contracts.

Swagger/OpenAPI contract

 The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.

An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.

-        Source : https://swagger.io/specification/

 

OpenAPI specs has a few major sections while defining the APIs:

-       Info

-       Tags

-       Paths

-       Components

Info: Holds API title, description, version, contact and license information.

Tags: Holds different tags for the API definitions, a useful way to segregate APIs, this is quite useful if you are using Swagger editor to navigate the APIs. You are can also use tags to document your APIs better.

Paths: As the name suggests, it holds all your API paths. It defines, the REST operation, description, request, response structures and HTTP response codes.

Components: This is to define the objects (models) you use in your API definitions also the reusable HTTP response codes.

 You can choose to write the specs in JSON or YAML. A basic example looks like below.

-source "swagger.io/docs/specification/basic-structure/"


While generating code using Maven plugin, paths and components are being leveraged to generate code. 

The example is based on my previous blog on Liquibase+Spring boot


 

Example API spec : API Spec for Providers/Services (I have excluded Citizen APIs for the time being)

 


 

As you can see above, I have defined 7 endpoints, with some standard info and a couple of tags.

 

Lets dive into one of the paths:

This is a get all services endpoint, which returns an array of “Service” objects (this is defined in components, that’s why a $ref). It also defines that it is being tagged as Service API and other HTTP error codes with a return message.


Above, the “operationId” will be later used to generate the controller method name.

 

How does a component looks like:


 

Here you define the basic object structure with some example values and also if this object also refers to another object within the components (such as Provider).

More info, on how to define such contracts using OAS can be found here.

Code generation

Code generation can be for server (the API implementation itself) or client (connecting the API). Although, for client you can still choose use Feign clients for more diverse and sophisticated implementation depending on your requirements.

I will concentrate on the server side of it, since that’s reduces a lot of boilerplate code for you.

 

The easiest way to do this, is to use https://editor.swagger.io/ and do this from the browser, if you choose to. But this won’t help you to make generation and maintenance easier.

 


Maven plugin

OpenAPI provides an useful maven plugin which you can use to generate the code from these types of contracts.

Link to repo is here.

 

The documentation talks about all the properties you can configure to generate server or a client. I will show you my example on the server part.


A few major properties are, where to find the yaml file containing the specs, package names for your generated classes.

With the spec, I shared earlier, if we use the above plugin, the generated classes looks like this:



 

FYI: I faced a few compilation errors, due to unused imports in the generated classes, which you can avoid by using a different template.

More info on:

-       https://github.com/OpenAPITools/openapi-generator/issues/8776

-       https://github.com/OpenAPITools/openapi-generator/issues/2901

 

I had to add some extra dependencies to resolve this, you can also do that temporarily to avoid compilation issues.


Closer look at the generated classes

API-Controller-Delegate

OpenAPI plugin generates 2 interfaces and 1 class. One interface for API which gets implemented by Controller, they both combined defines the endpoints.

There will be as many number of API-Controller combination as the number of “paths” you have defined in the yaml.

 


 

Another interface, xxxDelegate which should be implemented by a @Service implementation of Spring Boot.

The delegate interface, comes from the plugin config properties, delegatePattern = true. You can choose to disable this, but I find it quite useful from the perspective of “separation-of-concerns” concept.

Model

The plugin also generates all the model objects defined in the components section of the API spec.

This is a simple POJO with all defined properties from the spec with annotations defining non-nulls, required etc. attributes.

Complete the implementation with Service & Repository

Now that we have the basic code generated for the endpoints, we just need to implement the repository and service classes (and possibly the entities). In this example, I have also created the entities, since I like to keep the response-request objects separated from the DB structure.

BTW, the convertion between entity-to-response object has been done using Mapstruct.

 

The complete implementation is in Github.

Running the application 

If you just run the SerivceRepositoryApplication class, all the APIs will be available and you can invoke them using your favorite client.

 


Comments

Popular posts from this blog

Rich Text Editor - Oracle JET

Oracle JET has a lot of excellent UI components, but according to Murphy's law, client always comes up with something which you don't have at your disposal. So, driven by one of my client's requirements, I created a Rich Text Editor or WYSIWYG editor for Oracle JET. This is based on Quill JS and fully customizable. Github project download: https://github.com/sohamda/JET-Web-Components/tree/master/rich-text-editor I will explain in this blog, on how to integrate it in your own Oracle JET project. 1. Create and initialize your JET application and then put the downloaded web component inside "src\js\jet-composites" folder. 2. Once copied update your viewModel first. Add a snippet for passing the default content to be displayed by the editor after load. 3. Update view to load this editor Above you can see the "toolbar-options" property, that controls which options you should display to user on the editor. Those are basically the forma...

Exception Handling in ADF

This blog will give you an overview on how you can successfully deal with unhandled Runtime exceptions in an ADF application. This will give you an idea of: How to catch the unhandled exceptions. Write a separate log file with stacktrace and thread dumps. Redirect the user to an static error page #1. Catch unhandled exceptions :  Create a class "MyExceptionHandler" which extends : oracle.adf.view.rich.context.ExceptionHandler. Override handleException() method.     public void handleException(FacesContext facesContext, Throwable throwable, PhaseId phaseId) throws Throwable {         // this method is going to create a separate file with stacktrace and thread dumps         writeException(throwable);         // redirect to error page         redirectToErrorPage(facesContext);     }  Create a fo...

Layout Management & CSS Classes with Oracle JET

Oracle JET provides automatic responsive layout using CSS classes. So that, from large screens to small screens the application fits itself the best possible way. JET’s layout management are based on 2 types of CSS classes “Responsive Grid” and “Flex”. Responsive grid classes which deals with size, number of columns and functions of a particular <div>. Naming convention of these classes are oj- size - function - columns sizes can be: sm, md, lg, xl functions can be: hide, only-hide columns can be: any number between 1 to 12.   Just like Bootstrap, JET also divides the width of the available space into 12 columns, so for example, if you want a section of your page should take up atleast 5 columns if you divide the available screen into 12 columns, you need use : oj- size -5. Now comes the size part, you need to define that for each size of the screen, from hand-held mobile devices to large or extra large desktop screens. With combination with theses gr...