@abx/swagger-ui 中文文档教程
Swagger UI
Swagger UI 是 Swagger 项目的一部分。 Swagger 项目允许您生成、可视化和使用您自己的 RESTful 服务。 无需代理或第三方服务。 做你自己的方式。
Swagger UI 是一个无依赖性的 HTML、Javascript 和 CSS 资产集合,可以动态地 从符合 Swagger 标准的 API 生成漂亮的文档和沙箱。 因为 Swagger UI 没有依赖项,所以您可以在任何服务器环境或本地计算机上托管它。
What's Swagger?
Swagger™ 的目标是为 REST API 定义一个标准的、与语言无关的接口,允许人类和计算机发现和理解服务的功能,而无需访问源代码、文档或通过网络流量检查。 当通过 Swagger 正确定义时,消费者可以使用最少量的实现逻辑来理解远程服务并与之交互。 与接口为低级编程所做的类似,Swagger 消除了调用服务时的猜测。
查看 Swagger-Spec,了解有关 Swagger 项目的更多信息,包括支持其他语言的其他库等。
Compatibility
OpenAPI 规范自 2010 年首次创建以来经历了 4 次修订。swagger-ui 与 OpenAPI 规范之间的兼容性如下:
Swagger UI Version | Release Date | OpenAPI Spec compatibility | Notes | Status |
---|---|---|---|---|
2.1.4 | 2016-01-06 | 1.1, 1.2, 2.0 | tag v.2.1.4 | |
2.0.24 | 2014-09-12 | 1.1, 1.2 | tag v2.0.24 | |
1.0.13 | 2013-03-08 | 1.1, 1.2 | tag v1.0.13 | |
1.0.1 | 2011-10-11 | 1.0, 1.1 | tag v1.0.1 |
How to Use It
Download
您可以按原样使用 swagger-ui 代码! 无需构建或重新编译——只需克隆此存储库并使用 dist
文件夹中的预构建文件。 如果您按原样喜欢 swagger-ui,请到此为止。
Browser support
Swagger UI 适用于所有常青桌面浏览器(Chrome、Safari、Firefox)。 Internet Explorer 支持版本 8 (IE8) 及更高版本。
Build
你可以自己重建 swagger-ui 来调整它,或者你可以说你做了。 为此,请按照以下步骤操作:
Windows Users: Please install Python before follow below guidelines for node-gyp rebuild to run.
npm install
npm run build
- You should see the distribution under the dist folder. Open
./dist/index.html
to launch Swagger UI in a browser
Development
使用 npm run serve
进行新构建,观察更改,并在 http://localhost:8080/ 提供结果。
Build using Docker
使用 docker 容器构建 swagger-ui:
docker build -t swagger-ui-builder .
docker run -p 80:8080 swagger-ui-builder
这将在 http://localhost
启动 Swagger UI。
Use
打开 Swagger UI 后,它将加载 Swagger Petstore 服务并显示其 API。 您可以输入自己的服务器 url 并单击浏览以查看 API。
Customize
您可以选择为您的组织自定义 Swagger UI。 以下是其各个目录中内容的概述:
- dist: Contains a distribution which you can deploy on a server or load from your local machine.
- dist/lang: The swagger localization
- lib: Contains javascript dependencies which swagger-ui depends on
- node_modules: Contains node modules which swagger-ui uses for its development.
- src
- src/main/templates: handlebars templates used to render swagger-ui
- src/main/html: the html files, some images and css
- src/main/javascript: main code
SwaggerUi
要使用 swagger-ui,您应该查看 swagger-ui html 页面的来源 并对其进行自定义。 这基本上需要您实例化一个 SwaggerUi 对象并对其调用 load(),如下所示:
var swaggerUi = new SwaggerUi({
url:"http://petstore.swagger.io/v2/swagger.json",
dom_id:"swagger-ui-container"
});
swaggerUi.load();
Parameters
Parameter Name | Description |
---|---|
url | The url pointing to swagger.json (Swagger 2.0) or the resource listing (earlier versions) as per OpenAPI Spec. |
authorizations | An authorization object to be passed to swagger-js. Setting it here will trigger inclusion of any authorization or custom signing logic when fetching the swagger description file. Note the object structure should be { key: AuthorizationObject } |
spec | A JSON object describing the OpenAPI Specification. When used, the url parameter will not be parsed. This is useful for testing manually-generated specifications without hosting them. Works for Swagger 2.0 specs only. |
validatorUrl | By default, Swagger-UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators (Validator Badge). Setting it to null will disable validation. This parameter is relevant for Swagger 2.0 specs only. |
dom_id | The id of a dom element inside which SwaggerUi will put the user interface for swagger. |
booleanValues | SwaggerUI renders boolean data types as a dropdown. By default it provides a 'true' and 'false' string as the possible choices. You can use this parameter to change the values in dropdown to be something else, for example 0 and 1 by setting booleanValues to new Array(0, 1). |
docExpansion | Controls how the API listing is displayed. It can be set to 'none' (default), 'list' (shows operations for each resource), or 'full' (fully expanded: shows operations and their details). |
apisSorter | Apply a sort to the API/tags list. It can be 'alpha' (sort by name) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. |
operationsSorter | Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. |
defaultModelRendering | Controls how models are shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Model Schema' links.) It can be set to 'model' or 'schema', and the default is 'schema'. |
onComplete | This is a callback function parameter which can be passed to be notified of when SwaggerUI has completed rendering successfully. |
onFailure | This is a callback function parameter which can be passed to be notified of when SwaggerUI encountered a failure was unable to render. |
highlightSizeThreshold | Any size response below this threshold will be highlighted syntactically, attempting to highlight large responses can lead to browser hangs, not including a threshold will default to highlight all returned responses. |
supportedSubmitMethods | An array of of the HTTP operations that will have the 'Try it out!' option. An empty array disables all operations. This does not filter the operations from the display. |
oauth2RedirectUrl | OAuth redirect URL |
showRequestHeaders | Whether or not to show the headers that were sent when making a request via the 'Try it out!' option. Defaults to false . |
jsonEditor | Enables a graphical view for editing complex bodies. Defaults to false . |
- All other parameters are explained in greater detail below
HTTP Methods and API Invocation
swagger-ui 支持调用所有 HTTP 方法 API,包括 GET、PUT、POST、DELETE、PATCH、OPTIONS。 这些在 swagger-js 项目中处理,请参阅那里了解它们的具体用法。
Header Parameters
通过 swagger-js 中的可插入机制支持标头参数。 您可以查看 index.html 以了解如何动态设置标头:
// add a new SwaggerClient.ApiKeyAuthorization when the api-key changes in the ui.
$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
swaggerUi.api.clientAuthorizations.add("auth_name", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"));
}
})
这将在将 auth_name
安全方案作为其 swaggerDefinitions 的一部分的调用上添加带有值 key
的标头 api_key
。 您可以替换 query
以将值作为查询参数发送。
Custom Header Parameters - (For Basic auth etc)
如果您有一些需要随每个请求一起发送的标头参数,请使用以下标头:
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "XXXX", "header"));
注意! 您可以在单个请求中传递多个标头参数,只需为它们使用唯一的名称(key
在上面的示例中使用)。
Localization and translation
本地化文件位于 lang 目录中。 请注意,语言文件和翻译器默认情况下不包含在 SwaggerUI 中。 您需要手动添加它们。
要启用翻译,您应该在 Swagger 的 index.html(或您使用的另一个入口点)中附加接下来的两行
<script src='lang/translator.js' type='text/javascript'></script>
<script src='lang/en.js' type='text/javascript'></script>
。第一行脚本是翻译器,第二行是您的语言词素。
如果你想附加对新语言的支持,你只需要创建 lang/your_lang.js 并像在现有文件中一样填充它。
要为翻译附加新的 lexemex,您应该做两件事
- Add lexeme into the language file. Example of new line: "new sentence":"translation of new sentence".
- Mark this lexeme in source html with attribute data-sw-translate. Example of changed source:
<anyHtmlTag data-sw-translate>new sentence</anyHtmlTag>
or <anyHtmlTag data-sw-translate value='new sentence'/>
:
目前只有内部 html、title-attribute 和 value-attribute 会被翻译。
CORS Support
OR: How to deal with "Can't read from server. It may not have the appropriate access-control-origin settings."
CORS 是一种防止网站使用您的个人数据做坏事的技术。 大多数浏览器 + javascript 工具包不仅支持 CORS,而且强制执行它,这对支持 Swagger 的 API 服务器有影响。
您可以在此处阅读有关 CORS 的信息:http://www.w3.org/TR/cors。
有两种情况不需要对 CORS 支持执行任何操作:
- swagger-ui is hosted on the same server as the application itself (same host and port).
- The application is located behind a proxy that enables the required CORS headers. This may already be covered within your organization.
否则,需要为以下情况启用 CORS 支持:
- Your Swagger docs. For Swagger 2.0 it's the
swagger.json
and any externally$ref
ed docs, and for prior version it's theResource Listing
andAPI Declaration
files. - For the
Try it now
button to work, CORS needs to be enabled on your API endpoints as well.
Testing CORS Support
您可以使用以下三种技术之一验证 CORS 支持:
- Curl your API and inspect the headers. For instance:
$ curl -I "http://petstore.swagger.io/v2/swagger.json"
HTTP/1.1 200 OK
Date: Sat, 31 Jan 2015 23:05:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Content-Type: application/json
Content-Length: 0
这告诉我们 petstore 资源列表支持 OPTIONS 和以下标头: 内容类型
,api_key
,授权
。
- Try swagger-ui from your file system and look at the debug console. If CORS is not enabled, you'll see something like this:
XMLHttpRequest cannot load http://sad.server.com/v2/api-docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Swagger-UI 无法轻易显示此错误状态。
- Using the http://www.test-cors.org website. Keep in mind this will show a successful result even if
Access-Control-Allow-Headers
is not available, which is still required for Swagger-UI to function properly.
Enabling CORS
启用 CORS 的方法取决于您用来托管应用程序的服务器和/或框架。 http://enable-cors.org 提供了有关如何在一些常见 Web 服务器中启用 CORS 的信息。
其他服务器/框架可能会为您提供有关如何在其用例中具体启用它的信息。
CORS and Header Parameters
Swagger 让您可以轻松地将标头作为参数发送到请求。 您的 CORS 配置也支持这些标头的名称必须。 从我们上面的示例:
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Swagger-UI 只允许发送具有这些名称的标头。
How to Improve It
创建您自己的 swagger-api/swagger-ui 分支
要分享您的更改,提交拉取请求。
Change Log
请查看发布以获取更改日志。
License
版权所有 2016 SmartBear 软件
,根据 Apache 许可证 2.0 版(“许可证”)获得许可; 除非遵守许可证,否则您不得使用此文件。 您可以在 apache.org/licenses/LICENSE-2.0 获得许可证的副本,
除非适用法律要求或书面同意,软件 根据许可证分发是在“按原样”的基础上分发的, 没有任何明示或暗示的保证或条件。 请参阅许可证以获取特定语言的管理权限和 许可证下的限制。
Swagger UI
Swagger UI is part of the Swagger project. The Swagger project allows you to produce, visualize and consume your OWN RESTful services. No proxy or 3rd party services required. Do it your own way.
Swagger UI is a dependency-free collection of HTML, Javascript, and CSS assets that dynamically generate beautiful documentation and sandbox from a Swagger-compliant API. Because Swagger UI has no dependencies, you can host it in any server environment, or on your local machine.
What's Swagger?
The goal of Swagger™ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service.
Check out Swagger-Spec for additional information about the Swagger project, including additional libraries with support for other languages and more.
Compatibility
The OpenAPI Specification has undergone 4 revisions since initial creation in 2010. Compatibility between swagger-ui and the OpenAPI Specification is as follows:
Swagger UI Version | Release Date | OpenAPI Spec compatibility | Notes | Status |
---|---|---|---|---|
2.1.4 | 2016-01-06 | 1.1, 1.2, 2.0 | tag v.2.1.4 | |
2.0.24 | 2014-09-12 | 1.1, 1.2 | tag v2.0.24 | |
1.0.13 | 2013-03-08 | 1.1, 1.2 | tag v1.0.13 | |
1.0.1 | 2011-10-11 | 1.0, 1.1 | tag v1.0.1 |
How to Use It
Download
You can use the swagger-ui code AS-IS! No need to build or recompile--just clone this repo and use the pre-built files in the dist
folder. If you like swagger-ui as-is, stop here.
Browser support
Swagger UI works in all evergreen desktop browsers (Chrome, Safari, Firefox). Internet Explorer support is version 8 (IE8) and above.
Build
You can rebuild swagger-ui on your own to tweak it or just so you can say you did. To do so, follow these steps:
Windows Users: Please install Python before follow below guidelines for node-gyp rebuild to run.
npm install
npm run build
- You should see the distribution under the dist folder. Open
./dist/index.html
to launch Swagger UI in a browser
Development
Use npm run serve
to make a new build, watch for changes, and serve the result at http://localhost:8080/.
Build using Docker
To build swagger-ui using a docker container:
docker build -t swagger-ui-builder .
docker run -p 80:8080 swagger-ui-builder
This will start Swagger UI at http://localhost
.
Use
Once you open the Swagger UI, it will load the Swagger Petstore service and show its APIs. You can enter your own server url and click explore to view the API.
Customize
You may choose to customize Swagger UI for your organization. Here is an overview of what's in its various directories:
- dist: Contains a distribution which you can deploy on a server or load from your local machine.
- dist/lang: The swagger localization
- lib: Contains javascript dependencies which swagger-ui depends on
- node_modules: Contains node modules which swagger-ui uses for its development.
- src
- src/main/templates: handlebars templates used to render swagger-ui
- src/main/html: the html files, some images and css
- src/main/javascript: main code
SwaggerUi
To use swagger-ui you should take a look at the source of swagger-ui html page and customize it. This basically requires you to instantiate a SwaggerUi object and call load() on it as below:
var swaggerUi = new SwaggerUi({
url:"http://petstore.swagger.io/v2/swagger.json",
dom_id:"swagger-ui-container"
});
swaggerUi.load();
Parameters
Parameter Name | Description |
---|---|
url | The url pointing to swagger.json (Swagger 2.0) or the resource listing (earlier versions) as per OpenAPI Spec. |
authorizations | An authorization object to be passed to swagger-js. Setting it here will trigger inclusion of any authorization or custom signing logic when fetching the swagger description file. Note the object structure should be { key: AuthorizationObject } |
spec | A JSON object describing the OpenAPI Specification. When used, the url parameter will not be parsed. This is useful for testing manually-generated specifications without hosting them. Works for Swagger 2.0 specs only. |
validatorUrl | By default, Swagger-UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators (Validator Badge). Setting it to null will disable validation. This parameter is relevant for Swagger 2.0 specs only. |
dom_id | The id of a dom element inside which SwaggerUi will put the user interface for swagger. |
booleanValues | SwaggerUI renders boolean data types as a dropdown. By default it provides a 'true' and 'false' string as the possible choices. You can use this parameter to change the values in dropdown to be something else, for example 0 and 1 by setting booleanValues to new Array(0, 1). |
docExpansion | Controls how the API listing is displayed. It can be set to 'none' (default), 'list' (shows operations for each resource), or 'full' (fully expanded: shows operations and their details). |
apisSorter | Apply a sort to the API/tags list. It can be 'alpha' (sort by name) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. |
operationsSorter | Apply a sort to the operation list of each API. It can be 'alpha' (sort by paths alphanumerically), 'method' (sort by HTTP method) or a function (see Array.prototype.sort() to know how sort function works). Default is the order returned by the server unchanged. |
defaultModelRendering | Controls how models are shown when the API is first rendered. (The user can always switch the rendering for a given model by clicking the 'Model' and 'Model Schema' links.) It can be set to 'model' or 'schema', and the default is 'schema'. |
onComplete | This is a callback function parameter which can be passed to be notified of when SwaggerUI has completed rendering successfully. |
onFailure | This is a callback function parameter which can be passed to be notified of when SwaggerUI encountered a failure was unable to render. |
highlightSizeThreshold | Any size response below this threshold will be highlighted syntactically, attempting to highlight large responses can lead to browser hangs, not including a threshold will default to highlight all returned responses. |
supportedSubmitMethods | An array of of the HTTP operations that will have the 'Try it out!' option. An empty array disables all operations. This does not filter the operations from the display. |
oauth2RedirectUrl | OAuth redirect URL |
showRequestHeaders | Whether or not to show the headers that were sent when making a request via the 'Try it out!' option. Defaults to false . |
jsonEditor | Enables a graphical view for editing complex bodies. Defaults to false . |
- All other parameters are explained in greater detail below
HTTP Methods and API Invocation
swagger-ui supports invocation of all HTTP methods APIs including GET, PUT, POST, DELETE, PATCH, OPTIONS. These are handled in the swagger-js project, please see there for specifics on their usage.
Header Parameters
Header params are supported through a pluggable mechanism in swagger-js. You can see the index.html for a sample of how to dynamically set headers:
// add a new SwaggerClient.ApiKeyAuthorization when the api-key changes in the ui.
$('#input_apiKey').change(function() {
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
swaggerUi.api.clientAuthorizations.add("auth_name", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"));
}
})
This will add the header api_key
with value key
on calls that have the auth_name
security scheme as part of their swaggerDefinitions. You can substitute query
to send the values as a query param.
Custom Header Parameters - (For Basic auth etc)
If you have some header parameters which you need to send with every request, use the headers as below:
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "XXXX", "header"));
Note! You can pass multiple header params on a single request, just use unique names for them (key
is used in the above example).
Localization and translation
The localization files are in the lang directory. Note that language files and translator is not included in SwaggerUI by default. You need to add them manually.
To enable translation you should append next two lines in your Swagger's index.html (or another entry point you use)
<script src='lang/translator.js' type='text/javascript'></script>
<script src='lang/en.js' type='text/javascript'></script>
The first line script is a translator and the second one is your language lexemes.
If you wish to append support for new language you just need to create lang/your_lang.js and fill it like it's done in existing files.
To append new lexemex for translation you should do two things:
- Add lexeme into the language file. Example of new line: "new sentence":"translation of new sentence".
- Mark this lexeme in source html with attribute data-sw-translate. Example of changed source:
<anyHtmlTag data-sw-translate>new sentence</anyHtmlTag>
or <anyHtmlTag data-sw-translate value='new sentence'/>
.
At this moment only inner html, title-attribute and value-attribute are going to be translated.
CORS Support
OR: How to deal with "Can't read from server. It may not have the appropriate access-control-origin settings."
CORS is a technique to prevent websites from doing bad things with your personal data. Most browsers + javascript toolkits not only support CORS but enforce it, which has implications for your API server which supports Swagger.
You can read about CORS here: http://www.w3.org/TR/cors.
There are two cases where no action is needed for CORS support:
- swagger-ui is hosted on the same server as the application itself (same host and port).
- The application is located behind a proxy that enables the required CORS headers. This may already be covered within your organization.
Otherwise, CORS support needs to be enabled for:
- Your Swagger docs. For Swagger 2.0 it's the
swagger.json
and any externally$ref
ed docs, and for prior version it's theResource Listing
andAPI Declaration
files. - For the
Try it now
button to work, CORS needs to be enabled on your API endpoints as well.
Testing CORS Support
You can verify CORS support with one of three techniques:
- Curl your API and inspect the headers. For instance:
$ curl -I "http://petstore.swagger.io/v2/swagger.json"
HTTP/1.1 200 OK
Date: Sat, 31 Jan 2015 23:05:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Content-Type: application/json
Content-Length: 0
This tells us that the petstore resource listing supports OPTIONS, and the following headers: Content-Type
, api_key
, Authorization
.
- Try swagger-ui from your file system and look at the debug console. If CORS is not enabled, you'll see something like this:
XMLHttpRequest cannot load http://sad.server.com/v2/api-docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Swagger-UI cannot easily show this error state.
- Using the http://www.test-cors.org website. Keep in mind this will show a successful result even if
Access-Control-Allow-Headers
is not available, which is still required for Swagger-UI to function properly.
Enabling CORS
The method of enabling CORS depends on the server and/or framework you use to host your application. http://enable-cors.org provides information on how to enable CORS in some common web servers.
Other servers/frameworks may provide you information on how to enable it specifically in their use case.
CORS and Header Parameters
Swagger lets you easily send headers as parameters to requests. The name of these headers MUST be supported in your CORS configuration as well. From our example above:
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Only headers with these names will be allowed to be sent by Swagger-UI.
How to Improve It
Create your own fork of swagger-api/swagger-ui
To share your changes, submit a pull request.
Change Log
Please see releases for change log.
License
Copyright 2016 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.