Swagger与Debian集成的最佳实践主要包括以下几个方面:
pom.xml
中添加Springfox Swagger2和Swagger UI的依赖包。<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>
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestapi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger test")
.description("API描述")
.version("1.0")
.build();
}
}
/v1
。openapi: 3.0.0
info:
title: 电商平台API
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
/products/{id}:
get:
summary: 获取商品详情
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
'200':
description: 成功响应
content:
application/json:
schema:
$ref: '#/components/schemas/Product'
components:
schemas:
Product:
type: object
properties:
id:
type: string
name:
type: string
price:
type: number
openapi-generator-cli generate -i api-spec.yaml -g spring -o ./generated-code
swagger-mock-api
模拟API服务。const mockApi = require('swagger-mock-api');
mockApi({
swaggerFile: './api-spec.yaml',
port: 3000
});
requests
库进行自动化接口测试。import requests
def test_get_product():
response = requests.get("https://api.example.com/v1/products/123")
assert response.status_code == 200
assert response.json()["name"] == "Laptop"
@RestController
@RequestMapping("/api-docs")
public class ApiDocController {
@GetMapping
public String getApiDocs() {
return openApiDefinition;
}
}
通过以上步骤,可以在Debian系统上成功集成Swagger,并遵循最佳实践来提高API开发的效率和文档维护的便捷性。