一个功能强大的 Rust OpenAPI 3.1 库,提供 OpenAPI 规范的解析、验证和请求处理功能。
将以下内容添加到你的 Cargo.toml 文件中:
[dependencies]
openapi-rs = { git = "https://github.com/baerwang/openapi-rs", features = ["axum"] }
axum = "0.7"
use openapi_rs::model::parse::OpenAPI;
use openapi_rs::request::axum::RequestData;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 从 YAML 文件解析 OpenAPI 规范
// 你可以使用项目中的示例文件:examples/api.yaml
let content = std::fs::read_to_string("examples/api.yaml")?;
let openapi = OpenAPI::yaml(&content)?;
// 创建请求数据进行验证
let request_data = RequestData {
path: "/users".to_string(),
inner: axum::http::Request::builder()
.method("GET")
.uri("/users?page=1&limit=10")
.body(axum::body::Body::empty())
.unwrap(),
body: None,
};
// 根据 OpenAPI 规范验证请求
openapi.validator(request_data)?;
// 对于带请求体的 POST 请求
let body_data = r#"{"name": "John Doe", "email": "john.doe@example.com", "age": 30}"#;
let post_request = RequestData {
path: "/users".to_string(),
inner: axum::http::Request::builder()
.method("POST")
.uri("/users")
.header("content-type", "application/json")
.body(axum::body::Body::from(body_data))
.unwrap(),
body: Some(axum::body::Bytes::from(body_data)),
};
openapi.validator(post_request)?;
Ok(())
}
示例 OpenAPI 规范文件 (examples/api.yaml):
这个库包含一个完整的示例 OpenAPI 规范文件,展示了用户管理 API 的定义,包括:
email)uuid)date)time)date-time)ipv4)ipv6)base64)binary)minLength, maxLength)minimum, maximum)minItems, maxItems)required)enum)pattern)本库提供内置的可观测性功能,帮助在生产环境中监控调试验证操作。
可观测性系统生成包含以下信息的结构化日志:
成功验证:
INFO openapi_validation method="GET" path="/example/{uuid}" success=true duration_ms=2 timestamp=1642752000000
失败验证:
WARN openapi_validation method="GET" path="/example/{uuid}" success=false duration_ms=1 error="Invalid UUID format" timestamp=1642752000001
你可以运行包含的可观测性示例来查看日志记录的实际效果:
RUST_LOG=debug cargo run --example observability_test
详细实现请查看:observability_test.rs
运行测试:
cargo test
欢迎贡献代码!请遵循以下步骤:
git checkout -b feature/amazing-feature)git commit -m 'Add some amazing feature')git push origin feature/amazing-feature)本项目采用 Apache License 2.0 许可证 - 查看 LICENSE 文件了解详情。
$ claude mcp add openapi-rs \
-- python -m otcore.mcp_server <graph>