温馨提示×

Linux环境下Swagger如何实现API国际化

小樊
51
2025-07-29 07:08:29
栏目: 智能运维

在Linux环境下实现Swagger API文档的国际化可以通过以下几种方法:

1. 使用Swagger UI的多语言支持

  • 安装多语言版本的Swagger UI
    npm install swagger-ui-dist --save
    
  • 在HTML中配置
    <script src="node_modules/swagger-ui-dist/swagger-ui-bundle.js"></script>
    <script src="node_modules/swagger-ui-dist/swagger-ui-standalone-preset.js"></script>
    <script>
    window.onload = function() {
      const ui = SwaggerUIBundle({
        url: "your-api-spec.json",
        dom_id: '#swagger-ui',
        presets: [
          SwaggerUIBundle.presets.apis,
          SwaggerUIStandalonePreset
        ],
        plugins: [
          SwaggerUIBundle.plugins.DownloadUrl
        ],
        layout: "StandaloneLayout",
        // 设置语言
        locale: "zh-CN" // 可替换为其他语言代码如 en, fr, ja等
      });
    }
    </script>
    

2. API描述信息的国际化

  • 使用多份OpenAPI规范文件: 创建不同语言的API规范文件,例如 api_spec_en.json, api_spec_zh.json, api_spec_ja.json,并在每个文件中使用相应语言的描述信息。
  • 使用动态生成方式: 在Node.js应用中,根据请求头动态返回不同语言的描述:
    const express = require('express');
    const app = express();
    const swaggerJsdoc = require('swagger-jsdoc');
    app.get('/api-docs', (req, res) => {
      const acceptLanguage = req.headers['accept-language'] || 'en';
      const options = {
        definition: {
          openapi: '3.0.0',
          info: {
            title: getLocalizedTitle(acceptLanguage),
            description: getLocalizedDescription(acceptLanguage),
            version: '1.0.0',
          },
        },
        apis: ['./routes/*.js'],
      };
      const specs = swaggerJsdoc(options);
      res.json(specs);
    });
    function getLocalizedTitle(lang) {
      const titles = {
        'en': 'API Documentation',
        'zh': 'API文档',
        'ja': 'APIドキュメント'
      };
      return titles[lang] || titles['en'];
    }
    function getLocalizedDescription(lang) {
      const descriptions = {
        'en': 'This is the API documentation for our application.',
        'zh': '这是我们应用程序的API文档。',
        'ja': 'これが私たちのアプリケーションのAPIドキュメントです。'
      };
      return descriptions[lang] || descriptions['en'];
    }
    

3. 使用i18n工具处理描述文本

  • 集成i18n库
    npm install i18n --save
    
  • 配置i18n
    const i18n = require('i18n');
    i18n.configure({
      locales: ['en', 'zh', 'ja'],
      directory: __dirname + '/locales',
      defaultLocale: 'en'
    });
    
  • 在Swagger配置中使用
    const swaggerOptions = {
      info: {
        title: i18n.__('API Documentation'),
        description: i18n.__('API description goes here')
      }
    };
    

4. 使用API网关实现国际化

  • 在API网关层(如Nginx, Kong)实现内容协商
    location /api-docs {
      if ($http_accept_language ~* "^zh") {
        rewrite ^ /api-docs/zh last;
      }
      if ($http_accept_language ~* "^ja") {
        rewrite ^ /api-docs/ja last;
      }
      rewrite ^ /api-docs/en last;
    }
    

5. 使用Swagger插件实现

  • 对于Java Spring Boot项目,可以使用springdoc-openapi的国际化支持
    @Bean
    public OpenAPI customOpenAPI(LocaleResolver localeResolver) {
        return new OpenAPI()
            .info(new Info()
                .title(getLocalizedTitle(localeResolver))
                .description(getLocalizedDescription(localeResolver)));
    }
    private String getLocalizedTitle(LocaleResolver localeResolver) {
        Locale locale = localeResolver.resolveLocale(null);
        ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
        return bundle.getString("api.title");
    }
    

0