#Rocket #OAS
[[rocket_okapi]]を使う。
## 動く場合
すべて`0.4`系に揃える。
```rust
rocket = "0.4.10"
rocket_contrib = "0.4.10"
rocket_okapi = "0.4"
okapi = "0.4"
```
`/spec`で仕様書トップにアクセスできるようにする。そこで使う[[OpenAPI Specification]]に基づいたファイルは`/openapi`で取得できるファイル。
```rust:main.rs
use rocket;
use rocket_okapi::swagger_ui::{make_swagger_ui, SwaggerUIConfig};
pub fn main() {
let mut app = rocket::ignite()
.mount("/openapi", routes![api::openapi::index])
.mount(
"/spec/",
make_swagger_ui(&SwaggerUIConfig {
url: Option::Some("../openapi".to_owned()),
..Default::default()
}),
)
app.launch();
}
```
`/openapi`は`openapi.rs`と同一階層にある`openapi.yaml`を参照する。
```rust:openapi.rs
#[get("/")]
pub fn index() -> &'static str {
include_str!("openapi.yaml")
}
```
## エラーで動かない場合
==未解決==
ここが型エラーになる。
```rust
.mount(
"/swagger-ui/",
make_swagger_ui(&SwaggerUIConfig {
url: Option::Some("../openapi.json".to_owned()),
..Default::default()
}),
)
```
### 依存関係
```toml:cargo.toml
[dependencies]
rocket = "0.4.10"
rocket_okapi = "0.7.0-alpha-1"
schemars = "0.8.3"
okapi = { version = "0.6.0-alpha-1", features = ["derive_json_schema"] }
```
### `mount`が求める`Route`
```rust:router\route.rs 16行目
#[derive(Clone)]
pub struct Route {
/// The name of this route, if one was given.
pub name: Option<&'static str>,
/// The method this route matches against.
pub method: Method,
/// The function that should be called when the route matches.
pub handler: Box<dyn Handler>,
/// The base mount point of this `Route`.
pub base: Origin<'static>,
/// The uri (in Rocket's route format) that should be matched against. This
/// URI already includes the base mount point.
pub uri: Origin<'static>,
/// The rank of this route. Lower ranks have higher priorities.
pub rank: isize,
/// The media type this route matches against, if any.
pub format: Option<MediaType>,
/// Cached metadata that aids in routing later.
crate metadata: Metadata
}
```
### `make_swagger_ui`が求める`Route`
```rust:route\route.rs\s177行目
#[derive(Clone)]
pub struct Route {
/// The name of this route, if one was given.
pub name: Option<Cow<'static, str>>,
/// The method this route matches against.
pub method: Method,
/// The function that should be called when the route matches.
pub handler: Box<dyn Handler>,
/// The route URI.
pub uri: RouteUri<'static>,
/// The rank of this route. Lower ranks have higher priorities.
pub rank: isize,
/// The media type this route matches against, if any.
pub format: Option<MediaType>,
/// The discovered sentinels.
pub(crate) sentinels: Vec<Sentry>,
}
```