linux

如何在Linux上配置Swagger以支持多语言API文档

小樊
55
2025-08-31 06:03:00
栏目: 智能运维

在Linux上配置Swagger以支持多语言API文档,可以按照以下步骤进行:

1. 安装Swagger

首先,确保你已经在你的Linux系统上安装了Swagger。你可以使用npm(Node.js的包管理器)来安装Swagger。

sudo npm install -g swagger-ui-express

2. 创建Swagger配置文件

创建一个Swagger配置文件(通常是swagger.json),并在其中定义你的API规范。为了支持多语言,你可以在不同的路径下定义不同语言的API文档。

例如,创建两个文件:

swagger-en.json

{
  "swagger": "2.0",
  "info": {
    "title": "My API",
    "description": "This is my API documentation in English",
    "version": "1.0.0"
  },
  "paths": {
    "/api/items": {
      "get": {
        "summary": "Get items",
        "responses": {
          "200": {
            "description": "A list of items"
          }
        }
      }
    }
  }
}

swagger-zh.json

{
  "swagger": "2.0",
  "info": {
    "title": "我的API",
    "description": "这是我的API文档的中文版本",
    "version": "1.0.0"
  },
  "paths": {
    "/api/items": {
      "get": {
        "summary": "获取项目列表",
        "responses": {
          "200": {
            "description": "项目列表"
          }
        }
      }
    }
  }
}

3. 配置Express服务器

在你的Express应用中,配置Swagger UI以根据请求的语言加载相应的Swagger文档。

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const fs = require('fs');
const path = require('path');

const app = express();

// 根据请求头中的Accept-Language来确定语言
const getLanguage = () => {
  const acceptLanguage = req.headers['accept-language'];
  if (acceptLanguage && acceptLanguage.startsWith('zh')) {
    return 'zh';
  }
  return 'en';
};

// 加载相应的Swagger文档
const swaggerDocument = getLanguage() === 'zh' ? require('./swagger-zh.json') : require('./swagger-en.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

4. 测试多语言支持

启动你的Express服务器,并访问以下URL来测试多语言支持:

你可以通过设置请求头中的Accept-Language来切换语言:

curl -H "Accept-Language: zh" http://localhost:3000/api-docs

总结

通过以上步骤,你可以在Linux上配置Swagger以支持多语言API文档。关键在于创建不同语言的Swagger文档文件,并在Express服务器中根据请求的语言动态加载相应的文档。

0
看了该问题的人还看了