Skip to main content

Module openapi

Module openapi 

Source
Available on crate feature openapi only.
Expand description

OpenAPI 3.1 documents generated from registered routes, with request and response schemas from serde types.

Every route Router::route_entries knows becomes an operation (method, path, path parameters). Describe one further with an Operation — summary, JSON request body, responses, query parameters — whose schemas come from JsonSchema (#[derive(JsonSchema)], the same derivation MCP tools use for inputSchema/outputSchema, so it follows #[serde] renames). Rust has no runtime reflection, so the types are named where the operation is described rather than read off the handler. The document is OpenAPI 3.1, whose schema dialect is JSON Schema 2020-12 — what JsonSchema emits. No new dependency: the JSON is built by hand like the rest of the crate’s.

§Example

use rust_web_server::app::App;
use rust_web_server::openapi::{OpenApiConfig, Operation};
use rust_web_server::response::Response;
use rust_web_server::core::New;
use rust_web_server::JsonSchema;

#[derive(JsonSchema)]
struct User { id: u64, name: String }
#[derive(JsonSchema)]
struct NewUser { name: String }

let app = App::with_state(())
    .get("/users/:id", |_req, _params, _conn, _state| Response::new())
    .post("/users", |_req, _params, _conn, _state| Response::new())
    .openapi(
        OpenApiConfig::new("My API", "1.0.0")
            .operation("GET", "/users/:id", Operation::new("Look up a user").path_param::<u64>("id").response::<User>(200, "The user").status(404, "No such user"))
            .operation("POST", "/users", Operation::new("Create a user").body::<NewUser>().response::<User>(201, "Created")),
    );
// Serves GET /openapi.json (the document) and GET /docs (Swagger UI).

Structs§

OpenApiConfig
Metadata for the generated OpenAPI document, and the described operations.
Operation
What a client needs to know about one operation beyond its method and path. Schemas are JSON text, normally from JsonSchema.

Functions§

build_spec
Builds an OpenAPI 3.1 JSON document from routes and the operations in config.
swagger_ui_html
Self-contained Swagger UI HTML page, loading the swagger-ui-dist bundle from a CDN and pointing it at spec_url (typically /openapi.json).