在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配置的信息,請參考官方文檔。