StonehmSchema

Derive Macro StonehmSchema 

Source
#[derive(StonehmSchema)]
Expand description

Derive macro for automatic JSON schema generation.

This derive macro automatically implements the StonehmSchema trait for your types, enabling automatic JSON schema generation for OpenAPI specifications. Use this on all request and response types that you want to appear in your OpenAPI spec.

§Type Support

Supported Rust types and their JSON schema mappings:

  • String, &str"string"
  • i32, i64, u32, u64, etc. → "integer"
  • f32, f64"number"
  • bool"boolean"
  • Option<T> → makes field optional
  • Vec<T>"array" with item schema
  • Nested structs → object references
  • Enums → "string" (basic support)

§Examples

§Basic Struct

use serde::Serialize;
use stonehm_macros::StoneSchema;
 
#[derive(Serialize, StonehmSchema)]
struct User {
    id: u32,
    name: String,
    email: String,
    is_active: bool,
    age: Option<u32>,
}
 
// Generates JSON schema automatically
let schema = User::schema();

§Request/Response Types

 
#[derive(Deserialize, StonehmSchema)]
struct CreateUserRequest {
    name: String,
    email: String,
    preferences: UserPreferences,
}
 
#[derive(Serialize, StonehmSchema)]
struct UserResponse {
    id: u32,
    name: String,
    email: String,
    created_at: String,
}
 
#[derive(Serialize, Deserialize, StonehmSchema)]
struct UserPreferences {
    newsletter: bool,
    theme: String,
}

§Error Types

 
#[derive(Serialize, StonehmSchema)]
enum ApiError {
    UserNotFound { id: u32 },
    ValidationError { field: String, message: String },
    DatabaseError,
    NetworkTimeout,
}

§Generated Schema Format

The macro generates JSON schemas following the OpenAPI 3.0 specification:

{
  "title": "User",
  "type": "object",
  "properties": {
    "id": { "type": "integer" },
    "name": { "type": "string" },
    "email": { "type": "string" },
    "is_active": { "type": "boolean" },
    "age": { "type": "integer" }
  },
  "required": ["id", "name", "email", "is_active"]
}

§Usage with API Handlers

Use StonehmSchema types in your API handlers for automatic documentation:

 
/// Create a new user
#[api_handler]
async fn create_user(
    Json(request): Json<CreateUserRequest>  // Schema automatically included
) -> Result<Json<User>, ApiError> {         // Both schemas automatically included
    // Implementation
}

§Requirements

  • Your type must implement Serialize (for response types) or Deserialize (for request types)
  • The type must be used in a function signature annotated with #[api_handler]
  • For error types used in Result<T, E>, implement axum::response::IntoResponse