Swagger是一種RESTful API文檔化和交互的工具,在API開發中使用較為廣泛。同時,Swagger也提供了導出API文檔的功能,以便於開發人員和用戶查看API介面的相關信息。本文將從多個方面詳細闡述Swagger導出文檔的相關內容。
一、導出文檔格式
Swagger支持導出文檔的格式有:YAML、JSON、Markup和AsciiDoc。其中,YAML和JSON格式比較常見,Markup和AsciiDoc格式在實際開發中使用較少。
以YAML格式導出文檔為例:
swagger: '2.0' info: version: 1.0.0 title: Sample API description: A sample API basePath: /v1 produces: - application/json paths: /users: get: summary: Retrieves a list of users description: Retrieves a list of users responses: 200: description: A list of users schema: type: array items: $ref: '#/definitions/User' definitions: User: type: object properties: id: type: integer format: int64 name: type: string email: type: string
其中,swagger: ‘2.0’表示Swagger的版本;info中包含了API的基本信息;basePath指定了API的基礎路徑;produces指定了API的響應格式;paths中包含了API的具體路徑和操作;definitions中定義了API的數據模型。
二、導出文檔中的API信息
Swagger導出的API文檔中,通常包含以下信息:
1. API基本信息
API的基本信息包括:API的名稱、版本、描述、協議、主機名和API的基礎路徑等。
2. API路徑和操作
API的路徑和操作指的是API介面的具體路徑和對該路徑的操作,如GET、POST、PUT、DELETE等。針對每個操作,Swagger導出文檔通常包含以下信息:
- summary:操作的簡要描述
- description:操作的詳細描述
- parameters:操作的參數列表,包含參數名、參數類型、參數位置、是否必選、默認值等信息
- responses:操作執行後的響應列表,包含響應碼、響應描述、響應內容等信息
3. API數據模型
Swagger導出文檔中也包含了API的請求和響應數據模型的定義,方便開發人員對API數據進行理解和使用。
三、自定義文檔主題
Swagger導出文檔默認採用的是Swagger UI主題,但是,在實際開發中,我們有時需要對導出文檔的主題進行定製。Swagger支持通過配置Swagger UI參數,自定義文檔主題。以下是一個示例:
window.onload = function() { // Begin Swagger UI call region const ui = SwaggerUIBundle({ url: "http://petstore.swagger.io/v2/swagger.json", dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout", docExpansion: "none", operationsSorter: "alpha", configUrl: "/swagger-config.json", oauth2RedirectUrl: "http://localhost:8000/swagger/oauth2-redirect.html", discoveryUrls:[ "http://localhost:8000/apis/discovery" ], validatorUrl: "//online.swagger.io/validator" }) // End Swagger UI call region window.ui = ui }
其中,通過配置layout、docExpansion等參數可以改變文檔的主題風格。如:StandaloneLayout表示採用單獨的布局方式,docExpansion指定API列表是否默認展開等。
四、自定義導出文檔
除了自定義文檔主題之外,Swagger還支持自定義導出文檔。我們可以通過重寫Swagger自帶的DefaultSwagger2MarkupConfig類,來實現自定義導出文檔。以下是一個示例:
public class CustomSwagger2MarkupConfig extends DefaultSwagger2MarkupConfig { public CustomSwagger2MarkupConfig() { this.setPathsGroupedBy(GroupBy.TAGS); this.setInterDocumentCrossReferencesEnabled(false); this.setSeparatedDefinitionsEnabled(true); this.setGeneratedExamplesEnabled(true); this.setListDelimiter('|'); this.setBasePathPrefix("/api"); } }
其中,重寫了DefaultSwagger2MarkupConfig類的一些方法,實現了自定義文檔的一些特性。
五、結語
Swagger導出文檔是API開發中必不可少的一部分,通過本文的介紹,應該可以更好地了解Swagger導出文檔相關的細節和技巧。希望本文對大家有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/190517.html