rocket-autodocu-codegen

Crates.iorocket-autodocu-codegen
lib.rsrocket-autodocu-codegen
version0.9.1
sourcesrc
created_at2024-09-22 13:27:27.863762
updated_at2024-09-22 13:27:27.863762
descriptionMacros supporting rocket_autodocu
homepage
repositoryhttps://github.com/animi-labs/autodocu
max_upload_size
id1382970
size42,536
Artur Dibrova (riktikdev)

documentation

README

autodocu

autodocu: Download API Docs

Rocket-autodocu: Download API Docs

unsafe forbidden

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

Never have outdated documentation again. autodocu 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-autodocu currently includes RapiDoc and Swagger UI, but others can be used too.

Supported OpenAPI Spec: 3.0.0
Supported Rocket version (for rocket_autodocu): 0.5.0-rc.1

Example of generated documentation using autodocu:

Basic Usage

use rocket::{get, post, serde::json::Json};
use rocket_autodocu::{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()
            }),
        )
}

More examples

  • Json web API: Simple example showing the basics of autodocu.
  • UUID: Simple example showing basics, but using UUID's instead of normal u32/u64 id's.
  • Custom Schema: Shows how to add more/custom info to OpenAPI file and merge multiple modules into one OpenAPI file.
  • Secure Request Guard: Shows how to implement authentication methods into the OpenAPI file. It shows: No authentication, API keys, HTTP Auth, OAuth2, OpenID and Cookies.
  • Special types: Showing use of some more obscure types and there usage. (Still work in progress)

FAQ

  • Q: Can I generate code from my OpenAPI file?
    A: No, this crate only allows you to automatically generate the OpenAPI file from your code. There are other crates that (attempt to) do this. So:

    • Rust code (Rocket) --> OpenAPI == autodocu
    • OpenAPI --> Rust code != autodocu
  • Q: My (diesel) database does not implement OpenApiFromRequest.
    A: This is because the parameter does not show up in the path, query or body. So this is considered a Request Guard. There is a derive macro for this, but this does not work in combination with the #[database("...")] marco. You can solve this my implementing it manually, like this:

Implement `OpenApiFromRequest` for Diesel DB
use rocket_autodocu::request::{OpenApiFromRequest, RequestHeaderInput};
use rocket_autodocu::gen::OpenApiGenerator;
use rocket_sync_db_pools::{diesel, database};

#[database("sqlite_logs")]
pub struct MyDB;

impl<'r> OpenApiFromRequest<'r> for MyDB {
    fn from_request_input(
        _gen: &mut OpenApiGenerator,
        _name: String,
        _required: bool,
    ) -> rocket_autodocu::Result<RequestHeaderInput> {
        Ok(RequestHeaderInput::None)
    }
}
  • Q: ... does not implement JsonSchema?
    A: The JsonSchema implementation is handled by Schemars, make sure you enabled the right feature flags for it. If it is still not implemented open an issue in the Schemars repo.

  • Q: Can I add custom data to my OpenAPI spec?
    A: Yes, see the Custom Schema example. autodocu also has build in functions if you want to merge the OpenAPI objects manually.

  • Q: Can I use this with other web frameworks then Rocket?
    A: Yes, but not there are no other implementations right now. But you can use the autodocu crate independently and use Serde to create the json or yaml file.

Feature Flags

autodocu:

  • impl_json_schema: Implements JsonSchema for Schemars and autodocu types themselves.
  • preserve_order: Keep the order of struct fields in Schema and all parts of the OpenAPI documentation.

Rocket-autodocu:

  • preserve_order: Keep the order of struct fields in Schema and all parts of the OpenAPI documentation.
  • swagger: Enable Swagger UI for rendering documentation.
  • rapidoc: Enable RapiDoc for rendering documentation.
  • uuid: Enable UUID support in Rocket and Schemars.
  • msgpack: Enable msgpack support for Rocket. (when same Rocket feature flag is used.)
  • secrets: Enable secrets support for Rocket. (when same Rocket feature flag is used.)

Note that not all feature flags from Schemars are re-exported or enabled. So if you have objects for which the JsonSchema trait is not implemented, you might need to enable a feature flag in Schemars. For an example see the "uuid" example. (Make sure crate versions match)

How it works

This crate automatically generates an OpenAPI file when the Rocket server starts. The way this is done is shortly described here.

The Schemars crate provides us with the schemas for all the different structures and enums. autodocu does not implement any schemas directly, this is all handled by Schemars.

The autodocu crate just contains all the structures needed to create an OpenAPI file. This crate does not contain any code for the creation of them, just the structure and code to merge two OpenAPI structured together. This crate can be reused to create OpenAPI support in other web framework.

Rocket-autodocu crate contains all the code for generating the OpenAPI file and serve it once created. This code is usually executed using macro's like: mount_endpoints_and_merged_docs!{...}, openapi_get_routes![...], openapi_get_routes_spec![...] and openapi_get_spec![...] .

When the Rocket server is started (or wherever macro is placed) the OpenAPI file is generated once. This file/structure is then stored in memory and will be served when requested.

The Rocket-autodocu-codegen crate contains code for derive macros. #[openapi], rocket_autodocu::openapi_spec![...], rocket_autodocu::openapi_routes![...] and #[derive(OpenApiFromRequest)] in our case. This needs to be in a separate crate because of Rust restrictions. Note: derive or codegen crates are usually a bit hard to work with then other crates. So it is recommended to get some experience with how derive macros work before you change things in here.

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.

Commit count: 1

cargo fmt