在Linux環境下實現Swagger API文檔的國際化支持,可以通過以下幾種方法:
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>
使用多份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.',
'zh': '這是API文檔。',
'ja': 'これはAPIドキュメントです。'
};
return descriptions[lang] || descriptions['en'];
}
使用i18n工具處理描述文本:
集成i18n庫(如i18n),配置i18n:
const i18n = require('i18n');
i18n.configure({
locales: ['en', 'zh', 'ja'],
directory: __dirname + '/locales',
defaultLocale: 'en'
});
const swaggerOptions = {
info: {
title: i18n.__('API Documentation'),
description: i18n.__('API description goes here')
}
};
在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;
}
對于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");
}
推薦使用Springdoc,這是一個功能強大的開源API文檔工具,基于Spring構建,并提供多語言支持。只需在Swagger中定義API接口,Springdoc即可自動生成支持多種語言的詳細API文檔。
通過以上方法,您可以在Linux環境下輕松實現Swagger API文檔的國際化需求。