在Linux环境中自定义Swagger UI的展示,可以通过以下几种方法实现:
1. 使用Springfox-Swagger2和Springfox-Swagger-UI
如果你使用的是Spring Boot项目,可以通过添加springfox-swagger2
和springfox-swagger-ui
依赖来集成Swagger。然后通过配置类启用Swagger并定义基本信息。
配置步骤:
- 在
pom.xml
中添加依赖:
io.springfox springfox-swagger2 YOUR_DESIRED_VERSION io.springfox springfox-swagger-ui YOUR_DESIRED_VERSION
- 创建配置类启用Swagger:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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(); } }
- 启动Spring Boot项目后,访问
http://localhost:8080/swagger-ui.html
查看Swagger UI界面。
2. 使用FastAPI和Swagger UI
如果你使用的是FastAPI,可以通过以下步骤自定义Swagger UI的展示:
配置步骤:
- 安装FastAPI和相关模块:
pip install fastapi uvicorn python-multipart
- 创建FastAPI应用并添加Swagger UI支持:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="老王家猪肉炖粉条子API")
class Item(BaseModel):
name: str
qty: int
price: float
@app.get("/乱炖/")
async def read_items(白菜: str = "二斤", 粉条: str = "一把", 老抽: int = 3):
return {"火候掌握人": "王师傅", "成品": f"{白菜}配{粉条}炖三分钟,搁{老抽}勺老抽"}
- 访问
http://localhost:8000/docs
查看Swagger UI界面。
3. 使用Swagger UI和Express
如果你使用的是Node.js和Express,可以通过以下步骤自定义Swagger UI的展示:
配置步骤:
- 安装Swagger UI和相关模块:
npm install swagger-jsdoc swagger-ui-express
- 初始化Swagger JSdoc并配置:
const swaggerjsdoc = require('swagger-jsdoc'); const swaggerui = require('swagger-ui-express'); const swaggerdefinition = { openapi: '3.0.0', info: { title: '我的api文档', version: '1.0.0', description: '这是我的api文档的描述', }, servers: [{ url: 'http://localhost:3000', description: '开发服务器', }], }; const options = { swaggerdefinition, apis: ['./routes/*.js'], // 指向api文档的路径 }; const swaggerspec = swaggerjsdoc(options);
- 使用Swagger UI提供可视化界面:
app.use('/api-docs', swaggerui.serve, swaggerui.setup(swaggerspec));
- 启动Node.js应用后,通过访问
http://localhost:3000/api-docs
查看Swagger UI界面。
4. 自定义Swagger UI路径
如果你想要自定义Swagger UI的展示路径,可以在FastAPI应用中进行如下配置:
app = FastAPI(docs_url="/老王家的文档", openapi_tags=[{"name": "餐饮部", "description": "王师傅掌勺区"}])
这样,Swagger UI的文档将展示在/老王家的文档
路径下。
通过以上方法,你可以在Linux环境中自定义Swagger UI的展示,以满足不同的需求。