Home Java javaTutorial How to implement API annotation and document generation based on Spring Boot

How to implement API annotation and document generation based on Spring Boot

Jun 22, 2023 pm 12:04 PM
spring boot api comments Document generation

Spring Boot, as one of the most popular Java frameworks at present, has the advantages of rapid development, high integration, and easy testing. During the development process, we often need to write API documents to facilitate front-end and back-end collaboration and future project maintenance.

However, manually writing API documentation is very time-consuming and error-prone, so this article will introduce how to use Spring Boot's own annotations and some tools to automatically generate API comments and documentation.

1. Swagger

Swagger is currently one of the most popular Java API annotation and document generation tools. It can automatically generate API documentation by scanning annotations in Spring projects, and can also provide an interactive API exploration interface.

To use Swagger, you need to add the following dependencies to your Spring Boot project:

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency>

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>
Copy after login

Then, add the annotation @EnableSwagger2 in the Spring Boot startup class, as shown below:

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

Then, you can add annotations provided by Swagger to your Controller's methods to generate API documents.

For example, the following is a simple UserController:

@RestController
@RequestMapping("/user")
public class UserController {
  
   @ApiOperation(value = "获取用户列表", notes = "获取所有用户的列表")
   @GetMapping("/list")
   public List<User> getUserList() {
      return userService.getUserList();
   }
  
   @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
   @PostMapping("/")
   public String postUser(@RequestBody User user) {
      userService.saveUser(user);
      return "success";
   }
  
   @ApiOperation(value = "获取用户详情", notes = "根据id获取用户的详情")
   @GetMapping("/{id}")
   public User getUser(@PathVariable Long id) {
      return userService.getUserById(id);
   }
  
   @ApiOperation(value = "更新用户信息", notes = "根据id更新用户的信息")
   @PutMapping("/{id}")
   public String putUser(@PathVariable Long id, @RequestBody User user) {
      User u = userService.getUserById(id);
      if (u == null) {
          return "用户不存在";
      }
      userService.updateUser(user);
      return "success";
   }
  
   @ApiOperation(value = "删除用户", notes = "根据id删除用户")
   @DeleteMapping("/{id}")
   public String deleteUser(@PathVariable Long id) {
      User u = userService.getUserById(id);
      if (u == null) {
          return "用户不存在";
      }
      userService.deleteUser(id);
      return "success";
   }
}
Copy after login

By adding the annotation @ApiOperation and other related annotations, Swagger will automatically generate API documentation and provide an interactive API exploration interface.

You can view your API documentation by visiting http://localhost:8080/swagger-ui.html.

2. Spring REST Docs

Spring REST Docs is another Java API annotation and documentation generation tool that allows you to write API documentation using AsciiDoc, Markdown or HTML format.

Using Spring REST Docs, you need to add the following dependencies to your Spring Boot project:

<dependency>
   <groupId>org.springframework.restdocs</groupId>
   <artifactId>spring-restdocs-mockmvc</artifactId>
   <version>2.0.2.RELEASE</version>
</dependency>
Copy after login

Next, add the annotation @WebMvcTest in your test class, as follows:

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTests {
  
   @Autowired
   private MockMvc mockMvc;
  
   @Test
   public void getUserList() throws Exception {
      this.mockMvc.perform(get("/user/list"))
         .andExpect(status().isOk())
         .andDo(document("getUserList", 
             responseFields(
                 fieldWithPath("[].id").description("用户ID"),
                 fieldWithPath("[].name").description("用户名"),
                 fieldWithPath("[].age").description("用户年龄")
             )));
   }
  
   @Test
   public void postUser() throws Exception {
      User user = new User();
      user.setName("Tom");
      user.setAge(20);
      ObjectMapper mapper = new ObjectMapper();
      String userJson = mapper.writeValueAsString(user);
      this.mockMvc.perform(post("/user/")
         .contentType(MediaType.APPLICATION_JSON)
         .content(userJson))
         .andExpect(status().isOk())
         .andDo(document("postUser", 
             requestFields(
                 fieldWithPath("name").description("用户名"),
                 fieldWithPath("age").description("用户年龄")
             )));
   }
  
   @Test
   public void getUser() throws Exception {
      this.mockMvc.perform(get("/user/{id}", 1))
         .andExpect(status().isOk())
         .andDo(document("getUser", 
             pathParameters(
                 parameterWithName("id").description("用户ID")
             ),
             responseFields(
                 fieldWithPath("id").description("用户ID"),
                 fieldWithPath("name").description("用户名"),
                 fieldWithPath("age").description("用户年龄")
             )));
   }
  
   @Test
   public void putUser() throws Exception {
      User user = new User();
      user.setName("Tom");
      user.setAge(20);
      ObjectMapper mapper = new ObjectMapper();
      String userJson = mapper.writeValueAsString(user);
      this.mockMvc.perform(put("/user/{id}", 1)
         .contentType(MediaType.APPLICATION_JSON)
         .content(userJson))
         .andExpect(status().isOk())
         .andDo(document("putUser", 
             pathParameters(
                 parameterWithName("id").description("用户ID")
             ),
             requestFields(
                 fieldWithPath("name").description("用户名"),
                 fieldWithPath("age").description("用户年龄")
             )));
   }
  
   @Test
   public void deleteUser() throws Exception {
      this.mockMvc.perform(delete("/user/{id}", 1))
         .andExpect(status().isOk())
         .andDo(document("deleteUser", 
             pathParameters(
                 parameterWithName("id").description("用户ID")
             )));
   }
}
Copy after login

By adding corresponding annotations and field descriptions, Spring REST Docs will automatically generate API documentation and save it in the /target/generated-snippets directory, which you can convert into the final documentation format.

3. Summary

This article introduces two methods to implement API annotation and document generation based on Spring Boot. Swagger provides a convenient and easy-to-use method, and the generated documents are relatively intuitive and easy to understand, making it suitable for small projects or rapid development. Spring REST Docs provides a more flexible and customizable approach, which can be applied to more complex projects and scenarios that require higher quality API documentation.

No matter which method you choose, it is essential that the API documentation is correct, standardized and clear. It not only facilitates front-end and back-end collaboration, but also helps long-term maintenance of your project.

The above is the detailed content of How to implement API annotation and document generation based on Spring Boot. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Boot+MyBatis+Atomikos+MySQL (with source code) Spring Boot+MyBatis+Atomikos+MySQL (with source code) Aug 15, 2023 pm 04:12 PM

In actual projects, we try to avoid distributed transactions. However, sometimes it is really necessary to do some service splitting, which will lead to distributed transaction problems. At the same time, distributed transactions are also asked in the market during interviews. You can practice with this case, and you can talk about 123 in the interview.

Achieve multi-language support and international applications through Spring Boot Achieve multi-language support and international applications through Spring Boot Jun 23, 2023 am 09:09 AM

With the development of globalization, more and more websites and applications need to provide multi-language support and internationalization functions. For developers, implementing these functions is not an easy task because it requires consideration of many aspects, such as language translation, date, time and currency formats, etc. However, using the SpringBoot framework, we can easily implement multi-language support and international applications. First, let us understand the LocaleResolver interface provided by SpringBoot. Loc

How to use Spring Boot to build big data processing applications How to use Spring Boot to build big data processing applications Jun 23, 2023 am 09:07 AM

With the advent of the big data era, more and more companies are beginning to understand and recognize the value of big data and apply it to business. The problem that comes with it is how to handle this large flow of data. In this case, big data processing applications have become something that every enterprise must consider. For developers, how to use SpringBoot to build an efficient big data processing application is also a very important issue. SpringBoot is a very popular Java framework that allows

Implement ORM mapping based on Spring Boot and MyBatis Plus Implement ORM mapping based on Spring Boot and MyBatis Plus Jun 22, 2023 pm 09:27 PM

In the development process of Java web applications, ORM (Object-RelationalMapping) mapping technology is used to map relational data in the database to Java objects, making it convenient for developers to access and operate data. SpringBoot, as one of the most popular Java web development frameworks, has provided a way to integrate MyBatis, and MyBatisPlus is an ORM framework extended on the basis of MyBatis.

Integration and use of Spring Boot and NoSQL database Integration and use of Spring Boot and NoSQL database Jun 22, 2023 pm 10:34 PM

With the development of the Internet, big data analysis and real-time information processing have become an important need for enterprises. In order to meet such needs, traditional relational databases no longer meet the needs of business and technology development. Instead, using NoSQL databases has become an important option. In this article, we will discuss the use of SpringBoot integrated with NoSQL databases to enable the development and deployment of modern applications. What is a NoSQL database? NoSQL is notonlySQL

Building an ESB system using Spring Boot and Apache ServiceMix Building an ESB system using Spring Boot and Apache ServiceMix Jun 22, 2023 pm 12:30 PM

As modern businesses rely more and more on a variety of disparate applications and systems, enterprise integration becomes even more important. Enterprise Service Bus (ESB) is an integration architecture model that connects different systems and applications together to provide common data exchange and message routing services to achieve enterprise-level application integration. Using SpringBoot and ApacheServiceMix, we can easily build an ESB system. This article will introduce how to implement it. SpringBoot and A

Implementing HTML to HTMLDocx conversion in Vue: a simple and efficient document generation method Implementing HTML to HTMLDocx conversion in Vue: a simple and efficient document generation method Jul 22, 2023 am 08:49 AM

Implementing HTML to HTMLDocx conversion in Vue: a simple and efficient document generation method In modern web development, generating documents is a common requirement. HTML is the basic structure of Web pages, and DOCX is a common office document format. In some cases, we may need to convert HTML to DOCX format to meet specific needs. This article will introduce a simple and efficient method to use Vue to convert HTML to HTMLDocx. First, we need to install

Spring Boot implements MySQL read-write separation technology Spring Boot implements MySQL read-write separation technology Aug 15, 2023 pm 04:52 PM

How to achieve read-write separation, Spring Boot project, the database is MySQL, and the persistence layer uses MyBatis.

See all articles