在Linux系统中,Swagger配置文件的编写通常遵循OpenAPI规范。以下是一个基本的Swagger配置文件示例,用于描述一个简单的RESTful API。
sudo apt-get install swagger-ui-express
swagger.json
的文件,然后使用以下内容填充它:{
"openapi": "3.0.0",
"info": {
"title": "Sample API",
"description": "A sample API to demonstrate Swagger configuration",
"version": "1.0.0"
},
"servers": [
{
"url": "http://localhost:3000",
"description": "Local server"
}
],
"paths": {
"/api/v1/hello": {
"get": {
"summary": "Get a hello message",
"responses": {
"200": {
"description": "A successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {
"type": "string"
}
}
}
}
}
}
}
}
}
}
}
这个配置文件定义了一个简单的API,其中包含一个名为/api/v1/hello
的GET请求。当调用此端点时,它将返回一个包含message
属性的JSON对象。
app.js
的文件,并添加以下内容: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 at http://localhost:${PORT}`);
});
node app.js
现在,你可以在浏览器中访问http://localhost:3000/api-docs
,查看和测试你的API文档。
请注意,这只是一个简单的示例。你可以根据需要扩展和自定义Swagger配置文件,以满足你的API需求。更多关于OpenAPI规范和Swagger配置的信息,请参考官方文档。