前后端分离开发中,接口需要规范化、标准化、文档化,这里使用utoipa
OpenAPI是什么
OpenAPI 是一个规范,用于描述、生产、消费和可视化 RESTful 风格的 Web 服务。它提供了一种标准的、与编程语言无关的方式来定义 API 的接口,包括路径(endpoints)、操作(如 GET、POST 等 HTTP 方法)、请求和响应的格式、参数、安全机制等细节
添加crate
tokio = { version = "1", features = ["full"] }
axum = "0.7.7"
# openapi
utoipa = { version = "5.1.1", features = ["axum_extras", "debug"] }
# openapi 文档
utoipa-swagger-ui = { version = "8.0.0", features = ["axum"] }
utoipa-axum = { version = "0", features = ["debug"] }
serde = "1"
serde_json = "1"
配置
定义Api文档结构体
// 定义 API 文档结构体
#[derive(OpenApi)]
#[openapi(
tags(
// 指定标签信息,后续用标签区给api分组
(name = CUSTOMER_TAG, description = "Customer API endpoints"),
(name = ORDER_TAG, description = "Order API endpoints")
)
)]
struct ApiDoc;
定义健康检查内部路由
/// 获取健康检查
#[utoipa::path(
method(get, head), // 方法
path = "/api/health", // 路径
responses(
// 响应状态、描述、返回内容、类型
(status = OK, description = "Success", body = str, content_type = "text/plain")
)
)]
async fn health() -> &'static str {
"ok"
}
定义内部处理器(非必须),这里的路由是swagger的内部路由
mod inner {
pub mod secret_handlers {
/// swagger内部处理器
#[utoipa::path(get, path = "/api/inner/secret", responses((status = OK, body = str)))]
pub async fn get_secret() -> &'static str {
"secret"
}
/// swagger内部处理器
#[utoipa::path(
post,
path = "/api/inner/secret",
responses((status = OK, description = "OK"))
)]
pub async fn pos