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 config;
33mod schemas;
34mod spec;
35#[cfg(feature = "swagger-ui")]
36mod swagger;
37
38pub use config::OpenApiConfig;
39pub use schemas::{ErrorSchema, FieldErrorSchema, ValidationErrorSchema};
40pub use spec::{
41    ApiInfo, MediaType, OpenApiSpec, Operation, OperationModifier, Parameter, PathItem,
42    RequestBody, ResponseModifier, ResponseSpec, SchemaRef,
43};
44
45// Re-export utoipa's ToSchema derive macro as Schema
46pub use utoipa::ToSchema as Schema;
47// Re-export utoipa's IntoParams derive macro
48pub use utoipa::IntoParams;
49
50// Re-export utoipa types for advanced usage
51pub mod utoipa_types {
52    pub use utoipa::{openapi, IntoParams, Modify, OpenApi, ToSchema};
53}
54
55use bytes::Bytes;
56use http::{header, Response, StatusCode};
57use http_body_util::Full;
58
59/// Generate OpenAPI JSON response
60pub fn openapi_json(spec: &OpenApiSpec) -> Response<Full<Bytes>> {
61    match serde_json::to_string_pretty(&spec.to_json()) {
62        Ok(json) => Response::builder()
63            .status(StatusCode::OK)
64            .header(header::CONTENT_TYPE, "application/json")
65            .body(Full::new(Bytes::from(json)))
66            .unwrap(),
67        Err(_) => Response::builder()
68            .status(StatusCode::INTERNAL_SERVER_ERROR)
69            .body(Full::new(Bytes::from("Failed to serialize OpenAPI spec")))
70            .unwrap(),
71    }
72}
73
74/// Generate Swagger UI HTML response
75#[cfg(feature = "swagger-ui")]
76pub fn swagger_ui_html(openapi_url: &str) -> Response<Full<Bytes>> {
77    let html = swagger::generate_swagger_html(openapi_url);
78    Response::builder()
79        .status(StatusCode::OK)
80        .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
81        .body(Full::new(Bytes::from(html)))
82        .unwrap()
83}