在Debian环境下使用Swagger(现称为OpenAPI)进行API测试与验证,可以按照以下步骤进行:
sudo apt update
sudo apt install openjdk-11-jdk
sudo apt install maven
java -version
mvn -version
使用Spring Initializr创建一个新的Spring Boot项目,选择必要的依赖,例如springfox-boot-starter
。
在pom.xml
文件中添加Swagger依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
在application.yml
或application.properties
文件中配置Swagger:
springfox:
documentation:
swagger-ui:
enabled: true
使用以下命令启动Spring Boot项目:
mvn spring-boot:run
项目启动后,打开浏览器,访问以下URL来查看Swagger生成的API文档:
http://localhost:8080/swagger-ui/
在控制器类中使用Swagger注解来描述API接口:
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
@Api(tags = "Sample API")
public class SampleController {
@GetMapping("/hello")
@ApiOperation(value = "Say hello", response = String.class)
public String sayHello() {
return "Hello, World!";
}
@PostMapping("/data")
@ApiOperation(value = "Send data", requestBody = @io.swagger.annotations.ApiRequestBody(content = @io.swagger.annotations.ApiContent(schema = @io.swagger.annotations.ApiSchema(implementation = String.class))), response = String.class)
public String sendData(@RequestBody String data) {
return "Received: " + data;
}
}
http://<your-application-url>/swagger-ui.html
。sudo apt-get update
sudo apt-get install apt-transport-https curl
curl -sL https://dl.swagger.io/swagger-editor/releases/2.0.9/swagger-editor.tar.gz | tar xz -C /opts
sudo ln -s /opt/swagger-editor/swagger-editor.sh /usr/local/bin/swagger
File -> Import
选项导入你的Swagger JSON文件或从http://<your-application-url>/v2/api-docs
获取API文档。sudo apt-get update
sudo apt-get install apt-transport-https curl
curl -sL https://dl.swagger.io/swagger-codegen/releases/2.4.21/swagger-codegen-cli.tar.gz | tar xz -C /opts
sudo ln -s /opt/swagger-codegen-cli/bin/swagger /usr/local/bin/swagger
swagger generate client -i http://<your-application-url>/v2/api-docs -l java -o my-client
sudo apt-get update
sudo apt-get install postman
http://<your-application-url>/v2/api-docs
获取API文档。在Swagger规范文件中定义数据模型和验证规则:
swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger data validation
version: '1.0.0'
paths:
/users:
post:
summary: Create a new user
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: body
description: User object that needs to be added to the store
required: true
schema:
$ref: '#/definitions/User'
responses:
200:
description: An array of users
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
format: email
email:
type: string
format: email
required:
- name
- email
通过以上步骤,你可以在Debian环境下成功配置和使用Swagger来生成和管理API文档,并进行API测试与验证。