cargo-rustapi 0.1.443

The official CLI tool for the RustAPI framework. Scaffold new projects, run development servers, and manage database migrations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! OpenAPI Client Code Generation
//!
//! Generate type-safe API clients from OpenAPI specifications.

use anyhow::{Context, Result};
use clap::Args;
use std::fs;
use std::path::{Path, PathBuf};

/// Arguments for client generation command
#[derive(Args, Debug)]
pub struct ClientArgs {
    /// Path to OpenAPI spec file (JSON or YAML) or URL
    #[arg(short, long)]
    pub spec: String,

    /// Output directory for generated client
    #[arg(short, long, default_value = "./generated")]
    pub output: PathBuf,

    /// Target language: rust, typescript, python
    #[arg(short, long, default_value = "rust")]
    pub language: String,

    /// Client package/crate name
    #[arg(short, long)]
    pub name: Option<String>,
}

/// Execute the client generation command
pub async fn client(args: ClientArgs) -> Result<()> {
    println!("🔧 Generating API client from OpenAPI spec...");
    println!("   Spec: {}", args.spec);
    println!("   Language: {}", args.language);
    println!("   Output: {}", args.output.display());

    // Create output directory
    fs::create_dir_all(&args.output).context("Failed to create output directory")?;

    // Load spec
    let spec_content = load_spec(&args.spec).await?;

    // Parse spec
    let spec: serde_json::Value = if args.spec.ends_with(".yaml") || args.spec.ends_with(".yml") {
        serde_yaml::from_str(&spec_content).context("Failed to parse YAML spec")?
    } else {
        serde_json::from_str(&spec_content).context("Failed to parse JSON spec")?
    };

    // Get API info
    let title = spec["info"]["title"].as_str().unwrap_or("api");
    let version = spec["info"]["version"].as_str().unwrap_or("0.1.0");
    let client_name = args.name.unwrap_or_else(|| sanitize_name(title));

    println!("   API: {} v{}", title, version);
    println!("   Client name: {}", client_name);

    match args.language.as_str() {
        "rust" => generate_rust_client(&args.output, &client_name, &spec).await?,
        "typescript" | "ts" => {
            generate_typescript_client(&args.output, &client_name, &spec).await?
        }
        "python" | "py" => generate_python_client(&args.output, &client_name, &spec).await?,
        lang => anyhow::bail!(
            "Unsupported language: {}. Use rust, typescript, or python.",
            lang
        ),
    }

    println!("✅ Client generated successfully!");
    Ok(())
}

async fn load_spec(spec_path: &str) -> Result<String> {
    if spec_path.starts_with("http://") || spec_path.starts_with("https://") {
        #[cfg(feature = "remote-spec")]
        {
            // Load from URL
            let response = reqwest::get(spec_path)
                .await
                .context("Failed to fetch OpenAPI spec from URL")?;
            response
                .text()
                .await
                .context("Failed to read response body")
        }
        #[cfg(not(feature = "remote-spec"))]
        {
            anyhow::bail!(
                "Remote spec loading requires the 'remote-spec' feature. Use a local file instead."
            )
        }
    } else {
        // Load from file
        fs::read_to_string(spec_path).context("Failed to read OpenAPI spec file")
    }
}

fn sanitize_name(name: &str) -> String {
    name.to_lowercase()
        .replace([' ', '-'], "_")
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '_')
        .collect()
}

async fn generate_rust_client(output: &Path, name: &str, spec: &serde_json::Value) -> Result<()> {
    let src_dir = output.join("src");
    fs::create_dir_all(&src_dir)?;

    // Generate Cargo.toml
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = {{ version = "0.12", features = ["json"] }}
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
thiserror = "2"
tokio = {{ version = "1", features = ["full"] }}
"#
    );
    fs::write(output.join("Cargo.toml"), cargo_toml)?;

    // Generate lib.rs with client
    let base_url = get_base_url(spec);
    let endpoints = generate_rust_endpoints(spec);
    let models = generate_rust_models(spec);

    let lib_rs = format!(
        r#"//! Generated API client for {name}
//! 
//! Auto-generated by RustAPI CLI

use reqwest::{{Client, Response}};
use serde::{{Deserialize, Serialize}};
use thiserror::Error;

/// API client errors
#[derive(Error, Debug)]
pub enum ApiError {{
    #[error("HTTP error: {{0}}")]
    Http(#[from] reqwest::Error),
    #[error("API error: {{status}} - {{message}}")]
    Api {{ status: u16, message: String }},
}}

/// API client
pub struct ApiClient {{
    client: Client,
    base_url: String,
}}

impl Default for ApiClient {{
    fn default() -> Self {{
        Self::new("{base_url}")
    }}
}}

impl ApiClient {{
    /// Create a new API client with the given base URL
    pub fn new(base_url: impl Into<String>) -> Self {{
        Self {{
            client: Client::new(),
            base_url: base_url.into(),
        }}
    }}

    /// Create with custom reqwest client
    pub fn with_client(client: Client, base_url: impl Into<String>) -> Self {{
        Self {{
            client,
            base_url: base_url.into(),
        }}
    }}

{endpoints}
}}

// Models
{models}
"#
    );
    fs::write(src_dir.join("lib.rs"), lib_rs)?;

    println!("   Generated Rust client crate");
    Ok(())
}

fn get_base_url(spec: &serde_json::Value) -> String {
    spec["servers"]
        .as_array()
        .and_then(|s| s.first())
        .and_then(|s| s["url"].as_str())
        .unwrap_or("http://localhost:8080")
        .to_string()
}

fn generate_rust_endpoints(spec: &serde_json::Value) -> String {
    let mut endpoints = String::new();

    if let Some(paths) = spec["paths"].as_object() {
        for (path, methods) in paths {
            if let Some(methods) = methods.as_object() {
                for (method, operation) in methods {
                    let default_op_id = format!("{}_{}", method, path.replace('/', "_"));
                    let op_id = operation["operationId"].as_str().unwrap_or(&default_op_id);
                    let fn_name = to_snake_case(op_id);
                    let summary = operation["summary"].as_str().unwrap_or("");

                    let rust_path = path;

                    endpoints.push_str(&format!(
                        r#"
    /// {summary}
    pub async fn {fn_name}(&self) -> Result<Response, ApiError> {{
        let url = format!("{{}}{rust_path}", self.base_url);
        let response = self.client.{method}(&url).send().await?;
        Ok(response)
    }}
"#
                    ));
                }
            }
        }
    }

    endpoints
}

fn generate_rust_models(spec: &serde_json::Value) -> String {
    let mut models = String::new();

    if let Some(schemas) = spec["components"]["schemas"].as_object() {
        for (name, schema) in schemas {
            let struct_name = to_pascal_case(name);
            models.push_str(&format!("\n/// {name} model\n"));
            models.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
            models.push_str(&format!("pub struct {} {{\n", struct_name));

            if let Some(props) = schema["properties"].as_object() {
                for (prop_name, prop) in props {
                    let rust_type = json_type_to_rust(prop);
                    let field_name = to_snake_case(prop_name);
                    models.push_str(&format!("    pub {}: {},\n", field_name, rust_type));
                }
            }

            models.push_str("}\n");
        }
    }

    models
}

fn json_type_to_rust(prop: &serde_json::Value) -> String {
    match prop["type"].as_str() {
        Some("string") => "String".to_string(),
        Some("integer") => "i64".to_string(),
        Some("number") => "f64".to_string(),
        Some("boolean") => "bool".to_string(),
        Some("array") => {
            let items_type = json_type_to_rust(&prop["items"]);
            format!("Vec<{}>", items_type)
        }
        Some("object") => "serde_json::Value".to_string(),
        _ => "serde_json::Value".to_string(),
    }
}

async fn generate_typescript_client(
    output: &Path,
    name: &str,
    spec: &serde_json::Value,
) -> Result<()> {
    let base_url = get_base_url(spec);

    let client_ts = format!(
        r#"/**
 * Generated API client for {name}
 * Auto-generated by RustAPI CLI
 */

const BASE_URL = '{base_url}';

export interface ApiError {{
  status: number;
  message: string;
}}

export class ApiClient {{
  private baseUrl: string;

  constructor(baseUrl: string = BASE_URL) {{
    this.baseUrl = baseUrl;
  }}

  private async request<T>(method: string, path: string, body?: any): Promise<T> {{
    const response = await fetch(`${{this.baseUrl}}${{path}}`, {{
      method,
      headers: {{
        'Content-Type': 'application/json',
      }},
      body: body ? JSON.stringify(body) : undefined,
    }});

    if (!response.ok) {{
      throw {{ status: response.status, message: await response.text() }};
    }}

    return response.json();
  }}

  // Add generated methods here based on OpenAPI spec
}}

export default new ApiClient();
"#
    );

    fs::write(output.join("client.ts"), client_ts)?;

    // Generate package.json
    let package_json = format!(
        r#"{{
  "name": "{name}",
  "version": "0.1.0",
  "main": "client.ts",
  "types": "client.ts"
}}
"#
    );
    fs::write(output.join("package.json"), package_json)?;

    println!("   Generated TypeScript client");
    Ok(())
}

async fn generate_python_client(output: &Path, name: &str, spec: &serde_json::Value) -> Result<()> {
    let base_url = get_base_url(spec);

    let client_py = format!(
        r#"\"\"\"
Generated API client for {name}
Auto-generated by RustAPI CLI
\"\"\"

import requests
from typing import Any, Dict, Optional
from dataclasses import dataclass

BASE_URL = '{base_url}'

@dataclass
class ApiError(Exception):
    status: int
    message: str

class ApiClient:
    def __init__(self, base_url: str = BASE_URL):
        self.base_url = base_url
        self.session = requests.Session()
    
    def _request(self, method: str, path: str, **kwargs) -> Any:
        url = f"{{self.base_url}}{{path}}"
        response = self.session.request(method, url, **kwargs)
        
        if not response.ok:
            raise ApiError(response.status_code, response.text)
        
        return response.json()
    
    # Add generated methods here based on OpenAPI spec

# Default client instance
client = ApiClient()
"#
    );

    fs::write(output.join("client.py"), client_py)?;

    // Generate setup.py
    let setup_py = format!(
        r#"from setuptools import setup

setup(
    name='{name}',
    version='0.1.0',
    py_modules=['client'],
    install_requires=['requests>=2.28.0'],
)
"#
    );
    fs::write(output.join("setup.py"), setup_py)?;

    println!("   Generated Python client");
    Ok(())
}

fn to_snake_case(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        result.push(c.to_lowercase().next().unwrap_or(c));
    }
    result
}

fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}