在Linux上利用Swagger进行API设计,通常涉及以下几个步骤:
sudo apt update
sudo apt install -y nodejs npm
npm install -g swagger
或者下载Swagger Editor的Docker镜像并在Linux上运行:
docker pull swaggerapi/swagger-editor
docker run -p 8080:8080 swaggerapi/swagger-editor
npm install -g swagger-ui
或者下载Swagger UI的源码并在Linux上构建:
git clone https://github.com/swagger-api/swagger-ui.git
cd swagger-ui
npm install
npm run build
然后将构建好的文件复制到Web服务器的目录中,例如/var/www/html。
swagger.yaml
文件:swagger: '2.0'
info:
version: 1.0.0
title: 测试Swagger文档
description: 测试Swagger文档API
contact:
name: 行百里者
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: 手机号码
schema:
type: string
responses:
'200':
description: OK
启动Swagger:配置完成后,可以通过命令行启动Swagger,或者在浏览器中访问Swagger UI的配置URL来查看和使用Swagger。
测试API:在Swagger UI界面中,可以点击“TRY IT OUT”按钮来测试API请求,输入必要的参数,然后发送请求并查看返回结果。
如果你使用的是Spring Boot项目,可以集成Swagger2来自动生成API文档:
pom.xml
中添加Swagger2的依赖:<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>
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
通过以上步骤,你可以在Linux上利用Swagger进行API设计,包括安装、配置、使用Swagger Editor和Swagger UI,以及集成Spring Boot项目。Swagger提供了一个直观的界面来生成和测试API文档,从而简化了API的开发和维护过程。