2个版本
0.6.1 | 2021年7月7日 |
---|---|
0.6.0-alpha-1 | 2021年7月7日 |
#29 in #swagger
21KB
474 代码行
okapi(不要使用此版本,原始版本已更新)
为Rust项目生成OpenAPI(又称Swagger)文档的分叉版本,以启用一些新功能
只需更改Cargo.toml中的使用方式,添加“package”参数即可
okapi = { version = "0.x.x", features = ["derive_json_schema"], package = "okapi_fork" }
rocket_okapi = { version = "0.x.x", package = "rocket_okapi_fork" }
工作中!
基本用法
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate rocket_okapi;
use rocket_contrib::json::Json;
use rocket_okapi::swagger_ui::make_swagger_ui;
use serde::{Deserialize, Serialize};
use schemars::JsonSchema;
// Derive JsonSchema for and request/response models
#[derive(Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct User {
user_id: u64,
username: String,
#[serde(default)]
email: Option<String>,
}
// Add #[openapi] attribute to your routes
#[openapi]
#[get("/user/<id>")]
fn get_user(id: u64) -> Option<Json<User>> {
Some(Json(User {
user_id: id,
username: "bob".to_owned(),
email: None,
}))
}
// You can tag your routes to group them together
#[openapi(tag = "Users")]
#[post("/user", data = "<user>")]
fn create_user(user: Json<User>) -> Json<User> {
user
}
// You can skip routes that you don't want to include in the openapi doc
#[openapi(skip)]
#[get("/hidden")]
fn hidden() -> Json<&'static str> {
Json("Hidden from swagger!")
}
pub fn make_rocket() -> rocket::Rocket {
rocket::build()
// routes_with_openapi![...] will host the openapi document at openapi.json
.mount(
"/",
routes_with_openapi![get_user, hidden],
)
// You can optionally host swagger-ui too
.mount(
"/swagger-ui/",
make_swagger_ui(&SwaggerUIConfig {
url: "../openapi.json".to_owned(),
..Default::default()
}),
)
}
待办事项
- 测试
- 文档
- 基准/优化内存使用和分配
- 实现
OpenApiFrom___
/OpenApiResponder
以支持更多的rocket/rocket-contrib类型 - 允许自定义OpenAPI生成设置,例如
- 自定义JSON模式生成设置
- 更改文档托管的位置的路径
依赖项
~0.9–1.8MB
~38K SLoC