rustapi_openapi/
lib.rs

1//! OpenAPI documentation for RustAPI
2//!
3//! This crate provides OpenAPI specification generation and Swagger UI serving
4//! for RustAPI applications. It wraps `utoipa` internally while providing a
5//! clean public API.
6//!
7//! # Features
8//!
9//! - Automatic OpenAPI spec generation
10//! - Swagger UI serving at `/docs`
11//! - JSON spec at `/openapi.json`
12//! - Schema derivation via `#[derive(Schema)]`
13//!
14//! # Usage
15//!
16//! ```rust,ignore
17//! use rustapi_rs::prelude::*;
18//!
19//! #[derive(Serialize, Schema)]
20//! struct User {
21//!     id: i64,
22//!     name: String,
23//! }
24//!
25//! RustApi::new()
26//!     .route("/users", get(list_users))
27//!     .docs("/docs")
28//!     .run("127.0.0.1:8080")
29//!     .await
30//! ```
31
32mod spec;
33mod swagger;
34mod config;
35mod schemas;
36
37pub use config::OpenApiConfig;
38pub use spec::{OpenApiSpec, ApiInfo, Operation, PathItem, Parameter, ResponseSpec, OperationModifier, RequestBody, MediaType, SchemaRef, ResponseModifier};
39pub use schemas::{ErrorSchema, ValidationErrorSchema, FieldErrorSchema};
40
41// Re-export utoipa's ToSchema derive macro as Schema
42pub use utoipa::ToSchema as Schema;
43// Re-export utoipa's IntoParams derive macro
44pub use utoipa::IntoParams;
45
46// Re-export utoipa types for advanced usage
47pub mod utoipa_types {
48    pub use utoipa::{ToSchema, IntoParams, OpenApi, Modify, openapi};
49}
50
51use bytes::Bytes;
52use http::{Response, StatusCode, header};
53use http_body_util::Full;
54
55/// Generate OpenAPI JSON response
56pub fn openapi_json(spec: &OpenApiSpec) -> Response<Full<Bytes>> {
57    match serde_json::to_string_pretty(&spec.to_json()) {
58        Ok(json) => Response::builder()
59            .status(StatusCode::OK)
60            .header(header::CONTENT_TYPE, "application/json")
61            .body(Full::new(Bytes::from(json)))
62            .unwrap(),
63        Err(_) => Response::builder()
64            .status(StatusCode::INTERNAL_SERVER_ERROR)
65            .body(Full::new(Bytes::from("Failed to serialize OpenAPI spec")))
66            .unwrap(),
67    }
68}
69
70/// Generate Swagger UI HTML response
71pub fn swagger_ui_html(openapi_url: &str) -> Response<Full<Bytes>> {
72    let html = swagger::generate_swagger_html(openapi_url);
73    Response::builder()
74        .status(StatusCode::OK)
75        .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
76        .body(Full::new(Bytes::from(html)))
77        .unwrap()
78}
79