在Linux上利用Swagger进行API文档共享,可以按照以下步骤进行:
安装Docker:
sudo apt-get update
sudo apt-get install -y docker.io
sudo systemctl start docker
sudo systemctl enable docker
拉取Swagger Editor镜像:
docker pull swaggerapi/swagger-editor:v4.6.0
运行Swagger Editor容器:
docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
拉取Swagger UI镜像:
docker pull swaggerapi/swagger-ui:v4.15.5
运行Swagger UI容器:
docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
安装Node.js和npm:
sudo apt-get update
sudo apt-get install -y nodejs npm
下载并解压Swagger Editor和Swagger UI:
mkdir -p /opt/swagger
cd /opt/swagger
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
tar -xvf v3.16.1.tar.gz
rm v3.16.1.tar.gz
cd swagger-editor-3.16.1
npm install
nohup http-server -p 8080 &
下载并解压Swagger UI:
cd ..
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
npm run start
创建一个OpenAPI规范文件(通常为YAML或JSON格式),用于描述您的API。例如,一个名为swagger.yaml
的文件:
swagger: '2.0'
info:
title: 测试Swagger API文档
version: 1.0.0
description: 此文档用于测试Swagger API
contact:
name: 行百里er
url: https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI1MDU1MjkxOQ==
license:
name: MIT
url: http://opensource.org/licenses/MIT
schemes:
- http
host: traveler100.com
basePath: /api/v1
paths:
/user/{mobile}:
get:
summary: 获取用户信息 (根据手机号)
description: 根据提供的手机号获取用户信息
parameters:
- name: mobile
in: path
required: true
description: 用户手机号
type: string
responses:
'200':
description: 成功
schema:
type: object
properties:
username:
type: string
password:
type: string
生成API文档:
swagger generate spec -o ./swagger.json
启动Swagger服务:
swagger serve --no-open ./swagger.json
访问Swagger UI:
如果您使用Spring Boot项目,可以使用 springdoc
库来集成Swagger。
添加依赖:
在 pom.xml
中添加以下依赖:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.1.0</version>
</dependency>
配置Swagger: 创建一个配置类来启用Swagger:
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@OpenAPIDefinition(info = @Info(title = "Your API Title", version = "1.0", description = "Your API Description"))
public class SwaggerConfig {
// 这里可以添加更多的配置,如果需要的话
}
启动Spring Boot应用: 使用Maven构建并启动你的Spring Boot应用。
访问Swagger UI: 启动应用后,访问 http://localhost:8080/swagger-ui 即可查看生成的API文档。
通过以上步骤,您可以在Linux上成功搭建Swagger环境,实现API文档的共享和管理。