是的,Ubuntu上的Swagger(現在通常稱為OpenAPI)可以與其他服務集成。以下是一些常見的集成方法和步驟:
pom.xml文件中添加Springfox的依賴項。<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()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My RESTful API")
.description("Some custom description of API.")
.contact(new Contact("Name", "www.example.com", "email@example.com"))
.version("1.0")
.build();
}
}
npm install -g swagger-jsdoc swagger-ui-express
swagger.json的文件,這個文件將包含你的API定義。{
"swagger": "2.0",
"info": {
"title": "Sample API",
"description": "A sample API to demonstrate Swagger integration",
"version": "1.0.0"
},
"basePath": "/api",
"paths": {
"/users": {
"get": {
"summary": "List all users",
"responses": {
"200": {
"description": "An array of users",
"schema": {
"type": "array",
"items": {
"ref": "#/definitions/User"
}
}
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
}
}
}
}
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// ... 其他中間件和路由
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
http://localhost:3000/api-docs(或者你設置的相應端口),你應該能看到Swagger UI界面,其中包含了你的API文檔。你可以使用Docker來部署Swagger,這樣可以更輕松地管理和部署API文檔。以下是一個簡單的Dockerfile示例:
# 使用官方的OpenAPI基礎鏡像
FROM openapi:3.0.0
# 設置工作目錄
WORKDIR /app
# 將Swagger的配置文件和資源文件復制到容器中
COPY . /app
# 安裝Swagger依賴
RUN npm install
# 暴露Swagger UI的端口
EXPOSE 3000
# 啟動Swagger
CMD ["npm", "start"]
通過以上步驟,你可以在Ubuntu上成功配置Swagger,并與其他服務協同工作,實現API文檔的生成、查看和測試。