Boost Spring Boot REST APIs with Swagger2: A Step-by-Step Guide
This tutorial explains how to integrate Swagger2 into a Spring Boot RESTful API project, covering dependency setup, configuration, annotation usage, and UI testing, enabling automatic, maintainable API documentation for multiple client platforms.
Preparation
With the popularity of front‑end/back‑end separation and micro‑service architectures, Spring Boot is increasingly used to build RESTful API projects that serve iOS, Android, web, and other back‑end services. Manually maintaining API documentation is labor‑intensive and prone to inconsistencies.
Integrate Swagger2
Swagger2 can be seamlessly integrated into Spring Boot to generate documentation directly from code and provide an interactive UI for testing.
Step 1: Add the starter dependency
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>Step 2: Enable Swagger in the main class
@EnableSwagger2Doc
@SpringBootApplication
public class Chapter22Application {
public static void main(String[] args) {
SpringApplication.run(Chapter22Application.class, args);
}
}Step 3: Configure Swagger properties in application.properties:
swagger.title= spring-boot-starter-swagger
swagger.description= Starter for swagger 2.x
swagger.version=1.4.0.RELEASE
swagger.license= Apache License, Version 2.0
swagger.licenseUrl= https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl= https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name= didi
swagger.contact.url= http://blog.didispace.com
swagger.contact.email= [email protected]
swagger.base-package= com.didispace
swagger.base-path= /**After starting the application, visit http://localhost:8080/swagger-ui.html to see the generated documentation.
Add Documentation Content
Use Swagger annotations to enrich the API description: @Api, @ApiOperation for class and method descriptions. @ApiImplicitParam, @ApiModel, @ApiModelProperty for parameter and model details.
Example controller:
@Api(tags = "用户管理")
@RestController
@RequestMapping("/users")
public class UserController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());
@GetMapping("/")
@ApiOperation(value = "获取用户列表")
public List<User> getUserList() {
return new ArrayList<>(users.values());
}
@PostMapping("/")
@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@GetMapping("/{id}")
@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@PutMapping("/{id}")
@ApiImplicitParam(paramType = "path", dataType = "Long", name = "id", value = "用户编号", required = true, example = "1")
@ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@DeleteMapping("/{id}")
@ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
}
@Data
@ApiModel(description = "用户实体")
public class User {
@ApiModelProperty("用户编号")
private Long id;
@ApiModelProperty("用户姓名")
private String name;
@ApiModelProperty("用户年龄")
private Integer age;
}After adding the annotations and restarting the application, the Swagger UI displays Chinese descriptions for each endpoint.
API Documentation Access and Debugging
The Swagger UI not only shows the API definitions but also provides a "Try it out!" button. Users can modify request parameters, submit calls, and view responses directly from the browser, making testing fast and convenient.
Code Example
The complete project is available in the chapter2-2 directory of the following repositories:
GitHub: https://github.com/dyc87112/SpringBoot-Learning/tree/2.x
Gitee: https://gitee.com/didispace/SpringBoot-Learning/tree/2.x
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
