#axum #openapi #swagger #proc-macro #yaml #rust

okapi-operation

基于 okapi 生成 OpenAPI 操作规范的过程宏

10 个版本

0.3.0-rc32024 年 8 月 7 日
0.3.0-rc22024 年 7 月 18 日
0.3.0-rc12023 年 12 月 3 日
0.2.1 2023 年 5 月 9 日
0.1.1 2022 年 7 月 11 日

#308 in Web 编程

Download history 811/week @ 2024-04-26 572/week @ 2024-05-03 1122/week @ 2024-05-10 1423/week @ 2024-05-17 1104/week @ 2024-05-24 838/week @ 2024-05-31 795/week @ 2024-06-07 987/week @ 2024-06-14 1155/week @ 2024-06-21 1002/week @ 2024-06-28 660/week @ 2024-07-05 848/week @ 2024-07-12 1448/week @ 2024-07-19 1159/week @ 2024-07-26 1513/week @ 2024-08-02 1385/week @ 2024-08-09

5,778 每月下载量

MIT 许可证

75KB
1.5K SLoC

okapi-operation

Crates.io docs.rs CI

这是一个库,允许使用过程宏 #[openapi] 生成 OpenAPI 的操作定义(使用来自 okapi 包的类型)。

示例(使用 axum-integration 功能)。

use axum::{extract::Query, Json};
use okapi_operation::{axum_integration::*, *};
use serde::Deserialize;

#[derive(Deserialize, JsonSchema)]
struct Request {
    /// Echo data
    data: String,
}

#[openapi(
    summary = "Echo using GET request",
    operation_id = "echo_get",
    tags = "echo",
    parameters(
        query(name = "echo-data", required = true, schema = "std::string::String",),
        header(name = "x-request-id", schema = "std::string::String",)
    )
)]
async fn echo_get(query: Query<Request>) -> Json<String> {
    Json(query.0.data)
}

#[openapi(
    summary = "Echo using POST request",
    operation_id = "echo_post",
    tags = "echo"
)]
async fn echo_post(
    #[body(description = "Echo data", required = true)] body: Json<Request>,
) -> Json<String> {
    Json(body.0.data)
}

fn main() {
    let app = Router::new()
        .route("/echo/get", get(openapi_handler!(echo_get)))
        .route("/echo/post", post(openapi_handler!(echo_post)))
        .finish_openapi("/openapi", "Demo", "1.0.0")
        .expect("no problem");
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app.into_make_service()).await.unwrap()
}

特性

  • macro:启用 #[openapi] 宏的重导入(默认启用);
  • axum-integration:启用与 axum 包(https://github.com/tokio-rs/axum)的集成(实现某些 axum 类型的特性)
    • axum 的兼容性:由于集成严重依赖于 axum 类型,此包只能与少量(可能甚至只有一个)最新的 axum 版本兼容;
    • 当前支持的 axum 版本:0.7.x
  • yaml:启用在存在 Accept 报头且值为 yaml 的情况下以 yaml 格式提供服务规范的能力。否则,在值 json|*/* 或空的情况下,将提供 json(目前仅影响 axum-integration)。

待办事项

  • 支持在 MediaType 或 Parameter 上提供示例(通过 JsonSchema 宏支持类型示例)
  • 支持从函数定义中推断参数的模式
  • 支持在宏中重命名或更改路径到 okapi/schemars/okapi-operations
  • 更多示例
  • ...

依赖项

~2.5–5.5MB
~99K SLoC