Skip to content

Latest commit

 

History

History
107 lines (88 loc) · 3.6 KB

README.md

File metadata and controls

107 lines (88 loc) · 3.6 KB

okapi

okapi: Download API Docs

rocket-okapi: Download API Docs

unsafe forbidden

Automated OpenAPI (AKA Swagger) document generation for Rust/Rocket projects.

Never have outdated documentation again. Okapi will generate documentation for you while setting up the server. It uses a combination of Rust Doc comments and programming logic to document your API.

The generated OpenAPI files can then be used by various programs to visualize the documentation. Rocket-okapi currently includes RapiDoc and Swagger UI, but others can be used too.

Supported OpenAPI Spec: 3.0.0

Example of generated documentation using okapi:

Basic Usage

use rocket::{get, post, serde::json::Json};
use rocket_okapi::{openapi, openapi_get_routes, 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()
        // openapi_get_routes![...] will host the openapi document at `openapi.json`
        .mount(
            "/",
            openapi_get_routes![get_user, create_user, hidden],
        )
        // You can optionally host swagger-ui too
        .mount(
            "/swagger-ui/",
            make_swagger_ui(&SwaggerUIConfig {
                url: "../openapi.json".to_owned(),
                ..Default::default()
            }),
        )
}

TODO

  • Tests
  • Documentation
  • Benchmark/optimise memory usage and allocations
  • Implement OpenApiFrom___/OpenApiResponder for more rocket/rocket-contrib types
  • Allow customizing openapi generation settings, e.g.
    • custom json schema generation settings
    • change path the document is hosted at

License

This project is licensed under the MIT license.

All contributions to this project will be similarly licensed.

Footnotes

  1. More examples will be added, please open an issue if you have a good example.