How to Automatically Document API Endpoints via Swagger
Documentation of any code is usually the most boring part, and as a developer you probably always look for ways to automate it. One of the ways to do so is by creating your own automation. However, nowadays we can enjoy the luxury of a fast growing IT industry that brings lots of tools and frameworks to the table.
The complete source can be found here. This article will show code fragments.
The environment we will auto document with Swagger will be Java and Spring Boot API, together with the Gradle build tool. As usual my articles are related to the JAVA development environment.
1. First, like in any library, we need to add all the dependencies.
For Maven users:
For Gradle users:
2. The next step is to enable Swagger for full Spring Boot Application. This can be done in the following way:
Let’s understand the code. The @EnableSwagger2 annotation is telling the application and Swagger that this is our starting point and application. Then we have 2 @Bean annotated methods, or just beans.
The first (api) is a configuration for what to cover, where to look and where the documentation will be living (main path - / ). The second one (apiInfo) is the informational part of documentation: title, version, license, description, etc.
3. The next step will be to to create a main controller for Swagger, for opening Swagger UI via redirection to swagger-ui.html:@Controller
This code is quite simple: it is creating a GET request holder controller that is redirecting GET requests from the application / to the /swagger-ui.html, and that’s it.
4. The next and final step is to annotate API Controllers with @Api and @ApiOperation:
The @Api annotation should be used on top of the controller class and have a value of high level mapping, if there is one (it’s best practice to have one).
The @ApiOperation annotation can be on any method level that you want to cover with Swagger, and it may have value that is a short description of the endpoint.
That’s all folks. After executing the project we will have fully documented API endpoints. It will look like this:
This is Swagger’s main page, containing all the annotated API endpoints in the list, grouped by controllers.
And after expanding a few of endpoints to check more details:
That’s it! You can now save time and effort by automatically documenting your API endpoints with Swagger.
Looking to automate your API tests? Get your API Testing started with BlazeMeter.