4 releases
0.7.4 | Aug 2, 2021 |
---|---|
0.7.3 | Aug 2, 2021 |
0.7.2 | Jul 15, 2021 |
0.7.1 | Jul 7, 2021 |
#1216 in Encoding
2MB
1.5K
SLoC
This projects serves to enable automatic rendering of openapi.json
files, and provides
facilities to also serve the documentation alongside your api.
Usage
First, add the following lines to your Cargo.toml
[dependencies]
rocket_okapi = "0.5"
schemars = "0.8"
okapi = { version = "0.5", features = ["derive_json_schema"] }
To add documentation to a set of endpoints, a couple of steps are required. The request and
response types of the endpoint must implement JsonSchema
. Secondly, the function must be
marked with #[openapi]
. After that, you can simply replace routes!
with
routes_with_openapi!
. This will append an additional route to the resulting Vec<Route>
,
which contains the openapi.json
file that is required by swagger. Now that we have the json
file that we need, we can serve the swagger web interface at another endpoint, and we should be
able to load the example in the browser!
Example
use rocket::get;
use rocket::serde::json::Json;
use rocket_okapi::{openapi, routes_with_openapi, JsonSchema};
use rocket_okapi::swagger_ui::{make_swagger_ui, SwaggerUIConfig};
#[derive(serde::Serialize, JsonSchema)]
struct Response {
reply: String,
}
#[openapi]
#[get("/")]
fn my_controller() -> Json<Response> {
Json(Response {
reply: "show me the docs!".to_string(),
})
}
fn get_docs() -> SwaggerUIConfig {
use rocket_okapi::swagger_ui::UrlObject;
SwaggerUIConfig {
url: "/my_resource/openapi.json".to_string(),
urls: vec![UrlObject::new("My Resource", "/v1/company/openapi.json")],
..Default::default()
}
}
fn main() {
rocket::build()
.mount("/my_resource", routes_with_openapi![my_controller])
.mount("/swagger", make_swagger_ui(&get_docs()))
.launch();
}
Dependencies
~16–50MB
~813K SLoC