在Web應用程序中,RESTful API是一種通用的設計模式,用於設計強大,靈活和易於使用的API。隨着微服務和雲計算等技術的出現,越來越多的企業使用RESTful API建立自己的應用,使其更具可擴展性和互操作性。
然而,RESTful API不是只需要設計一下就可以輕易實現的。為了使您的API符合一些標準和最佳實踐,您需要在您的API文檔中提供準確的描述,這就需要你去構建RESTful API文檔。在這方面,springdoc是一個非常不錯的選擇。
一、快速入門
springdoc是一個用於構建RESTful API文檔的庫。它使用spring-mvc和spring-boot來自動生成文檔,並使用OpenAPI(Swagger)規範來編寫文檔。在本節中,我們將學習如何在您的應用程序中使用springdoc來生成和提供文檔。
首先,您需要將springdoc添加到您的Maven項目中:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.2</version>
</dependency>
然後,在您的主應用程序類上添加@EnableSwagger2注釋:
@EnableSwagger2
@SpringBootApplication
public class MyApp {
// ...
}
接下來,定義一些RESTful API並為每個API添加說明:
@RestController
public class MyController {
@GetMapping("/hello")
@ApiOperation(value = "Say hello", notes = "Just for demo")
public String hello() {
return "Hello, world!";
}
}
您可以在@RequestMapping或@GetMapping注釋的URL路徑中包含變量。例如:
@GetMapping("/persons/{id}")
@ApiOperation(value = "Get a person", notes = "Get a person by id.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 404, message = "Not found"),
@ApiResponse(code = 500, message = "Server error")
})
public Person getPerson(@PathVariable Long id) {
// ...
}
最後,在應用程序中啟動springdoc,並訪問網址http://localhost:8080/swagger-ui.html,您將獲得自動生成的RESTful API文檔。您可以在文檔中添加其他的說明和注釋。
二、生成規範
springdoc不僅自動生成RESTful API文檔,還可以生成OpenAPI規範。
您可以通過在應用程序中設置以下屬性來配置生成的規範:
springdoc.swagger-ui.title=My API
springdoc.swagger-ui.description=My API description
springdoc.swagger-ui.version=1.0.0
springdoc.swagger-ui.termsOfServiceUrl=https://example.com/terms
springdoc.swagger-ui.contact.name=My Name
springdoc.swagger-ui.contact.email=myname@example.com
springdoc.swagger-ui.contact.url=https://example.com
springdoc.swagger-ui.license.name=Apache 2.0
springdoc.swagger-ui.license.url=https://www.apache.org/licenses/LICENSE-2.0.html
springdoc.swagger-ui.base-url=/api
您可以使用Swagger Editor對生成的規範進行進一步編輯和自定義。
三、自定義UI
springdoc UI可以通過多種方式進行自定義,以滿足您的個性化要求,例如:
- 更改UI顏色,圖標和布局
- 在文檔中添加註釋和說明
- 添加自定義UI元素,例如搜索框,網站地圖和其他頁面元素
- 支持多語言和Internationalization
您只需按照springdoc UI定製規則創建自己的CSS樣式表即可。以下是一個簡單的示例:
/* 設置UI顏色 */
.swagger-ui .opblock-post .opblock-summary-method {
background-color: #4caf50;
color: #fff;
}
/* 添加註釋 */
.swagger-ui .opblock-description {
font-style: italic;
}
/* 添加搜索框 */
.swagger-ui .topbar-wrapper .download-url-wrapper {
display: none;
}
.swagger-ui .topbar-wrapper {
justify-content: space-between;
}
.swagger-ui .topbar .filter {
display: block;
width: 240px;
margin-right: 8px;
border-radius: 4px;
border-color: #ddd;
}
如果需要更高級的UI自定義,請參考springdoc UI定製文檔。
四、結論
springdoc是一個非常實用的工具,可以幫助您自動生成RESTful API文檔,而不需要手動撰寫文檔。 springdoc還提供了簡單易用的界面和多種自定義選項,以滿足您的個性化需求。如果您正在使用spring-mvc或spring-boot,那麼springdoc是一個值得一試的工具。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/271318.html