DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How Spring Boot Starters Integrate With Your Project
  • Integrate Spring With Open AI
  • Spring Boot: User Login API Test Client Using Rest Assured
  • Spring Boot Delete User Details API Test Client Using Rest Assured | API Testing Using Rest Assured

Trending

  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots
  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  • Advancing Robot Vision and Control
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Automatically Document API Endpoints via Swagger

How to Automatically Document API Endpoints via Swagger

No one likes doing documentation. Here's a way for developers to automate generation of API endpoint documentation using Swagger.

By 
Grigor Avagyan user avatar
Grigor Avagyan
·
Aug. 11, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
18.9K Views

Join the DZone community and get the full member experience.

Join For Free

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.

One of these tools is Swagger, and in this article, we will learn how to automate documentation of API Endpoints via Swagger.

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:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

For Gradle users:

compile group: 'io.springfox', name: 'springfox-swagger2', version: '2.7.0'
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.7.0'

2. The next step is to enable Swagger for full Spring Boot Application. This can be done in the following way:

@EnableSwagger2
@SpringBootApplication
public class BlazeMeterApi {
   public static void main(String[] args) {
       SpringApplication.run(BlazeMeterApi.class, args);
   }

   @Bean
   public Docket api() {
       return new Docket(DocumentationType.SWAGGER_2).select()
               .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
               .paths(PathSelectors.any()).build().pathMapping("/")
               .apiInfo(apiInfo()).useDefaultResponseMessages(false);
   }

   @Bean
   ApiInfo apiInfo() {
       final ApiInfoBuilder builder = new ApiInfoBuilder();
       builder.title("BlazeMeter Spring Boot API").version("1.0").license("(C) Copyright BlazeMeter")
               .description("List of all endpoints used in API");
       return builder.build();
   }
}

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 create a main controller for Swagger, for opening Swagger UI via redirection to swagger-ui.html:@Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class RootController {
   @RequestMapping(method = RequestMethod.GET)
   public String swaggerUi() {
       return "redirect:/swagger-ui.html";
   }
}

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:

@Controller
@RequestMapping(value = VERSION + ARRIVAL)
@Api(value = VERSION + ARRIVAL)
public class ArrivalController {

   @Autowired
   private ArrivalRepository arrivalRepository;

   @ApiOperation(value = "Get all arrivals")
   @RequestMapping(value = "all", method = GET)
   @ResponseBody
   public List<Arrival> getAllArrivals() {
       return arrivalRepository.findAll();
   }

   @ApiOperation(value = "Get arrival by ID")
   @RequestMapping(value = "{id}", method = GET)
   @ResponseBody
   public Arrival getArrivalById(@PathVariable(value = "id") int id) {
       return arrivalRepository.findAllById(id);
   }
}

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 a 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:

automated api documentation with swagger

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:

swagger, api testing, documentation

That’s it! You can now save time and effort by automatically documenting your API endpoints with Swagger.

API Spring Framework Spring Boot Document

Published at DZone with permission of , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How Spring Boot Starters Integrate With Your Project
  • Integrate Spring With Open AI
  • Spring Boot: User Login API Test Client Using Rest Assured
  • Spring Boot Delete User Details API Test Client Using Rest Assured | API Testing Using Rest Assured

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!