Skip to content

Commit

Permalink
Add /docs endpoint to retrieve OpenAPI documentation (MystenLabs#713)
Browse files Browse the repository at this point in the history
  • Loading branch information
arun-koshy authored Mar 10, 2022
1 parent 18568c9 commit 30ada65
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions sui/src/rest_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ async fn main() -> Result<(), String> {

let mut api = ApiDescription::new();

// [DOCS]
api.register(docs).unwrap();

// [DEBUG]
api.register(genesis).unwrap();
api.register(sui_start).unwrap();
Expand All @@ -66,11 +69,12 @@ async fn main() -> Result<(), String> {
api.register(call).unwrap();
api.register(sync).unwrap();

api.openapi("Sui API", "0.1")
.write(&mut std::io::stdout())
let documentation = api
.openapi("Sui API", "0.1")
.json()
.map_err(|e| e.to_string())?;

let api_context = ServerContext::new();
let api_context = ServerContext::new(documentation);

let server = HttpServerStarter::new(&config_dropshot, api, api_context, &log)
.map_err(|error| format!("failed to create server: {}", error))?
Expand All @@ -83,6 +87,7 @@ async fn main() -> Result<(), String> {
* Server context (state shared by handler functions)
*/
struct ServerContext {
documentation: serde_json::Value,
genesis_config_path: String,
wallet_config_path: String,
network_config_path: String,
Expand All @@ -96,8 +101,9 @@ struct ServerContext {
}

impl ServerContext {
pub fn new() -> ServerContext {
pub fn new(documentation: serde_json::Value) -> ServerContext {
ServerContext {
documentation,
genesis_config_path: String::from("genesis.conf"),
wallet_config_path: String::from("wallet.conf"),
network_config_path: String::from("./network.conf"),
Expand All @@ -110,6 +116,35 @@ impl ServerContext {
}
}

/**
Response containing the API documentation.
*/
#[derive(Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct DocumentationResponse {
/** A JSON object containing the OpenAPI definition for this API. */
documentation: serde_json::Value,
}

/**
Generate OpenAPI documentation.
*/
#[endpoint {
method = GET,
path = "/docs",
tags = [ "docs" ],
}]
async fn docs(
rqctx: Arc<RequestContext<ServerContext>>,
) -> Result<HttpResponseOk<DocumentationResponse>, HttpError> {
let server_context = rqctx.context();
let documentation = &server_context.documentation;

Ok(HttpResponseOk(DocumentationResponse {
documentation: documentation.clone(),
}))
}

/**
Request containing the server configuration.
Expand Down

0 comments on commit 30ada65

Please sign in to comment.