Spring boot: Documenting an Microservices using Swagger

Today I would like to share simple but helpful concept for documenting an API using swagger. In traditional approach people are creating a document to to show API detail. We are facing multiple issue in approach like

  • We need to change a document if API changed.
  • For very large project it would be hard to manage n number of services.

We have library available for better API documentation and which overcome above issues.

What is swagger

The Java based library called swagger which is provided by SpringFox will help us to create API documentation.

Official Swagger Git is : https://github.com/swagger-api

You just need to make small changes to some files to enable swagger.
Let’s look all of them in detail.
You can clone repository from below git.
GitHub Repo: https://github.com/yogeshmprajapati/kode12-spring-boot.git
Git Module: spring-boot-document-microservice-swagger

pom.xml

Add following dependency in you pom.

EmployeeController.java

Sample controller to show how swagger interpret methods.

SpringBootDocumentMicroserviceSwaggerApplication.java

Class having main method to run an application.

The notifiable thing here is @EnableSwagger2, this annotation is required to enable swagger for current application and swagger will scan all web services signatures and populate it using swagger-ui.

Run an application

Run your application using main method and hit URL below to your favorite browser.
http://localhost:8080/swagger-ui.html

You will get the output as shown in below screenshot.
swagger output 1

Here, it shows all exposed controller, one(basic-error-controller) which is exposed by spring and employee-controller is created by us.

Once we click on employee-controller, it shows all methods created in particular controller with details like URI pattern, return type, method name etc.

swagger output 2

Once we click on second method (/employee/{employeeId}) it shows sample response value and also provide a view to test particular service.

swagger output 3

That’s it about Swagger, SpringFox will provide multiple modules to do more with our application. I will cover some of them in upcoming posts.

Share current post by copy: https://goo.gl/UjwVF3
Happy Learning!
:)

Thanks,
Yogesh P