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
//! Example: Generate a complete HTTP client from an OpenAPI specification
//!
//! This example demonstrates how to:
//! 1. Load an OpenAPI spec
//! 2. Configure the generator with retry and tracing
//! 3. Generate a complete HTTP client
//! 4. Save the generated code to files
//!
//! Run this example:
//! ```bash
//! cargo run --example generate_full_client
//! ```
use openapi_to_rust::{CodeGenerator, GeneratorConfig, analysis::SchemaAnalyzer};
use serde_json::json;
use std::path::PathBuf;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🚀 OpenAPI HTTP Client Generator Example\n");
// 1. Create a sample OpenAPI specification
println!("📝 Creating sample OpenAPI specification...");
let spec = json!({
"openapi": "3.0.0",
"info": {
"title": "Todo API",
"version": "1.0.0",
"description": "A simple Todo API for demonstration"
},
"servers": [
{
"url": "https://api.example.com/v1"
}
],
"paths": {
"/todos": {
"get": {
"operationId": "listTodos",
"summary": "List all todos",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Todo"
}
}
}
}
}
}
},
"post": {
"operationId": "createTodo",
"summary": "Create a new todo",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/CreateTodoRequest"
}
}
}
},
"responses": {
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Todo"
}
}
}
}
}
}
},
"/todos/{id}": {
"get": {
"operationId": "getTodo",
"summary": "Get a specific todo",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Todo"
}
}
}
}
}
},
"put": {
"operationId": "updateTodo",
"summary": "Update a todo",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/UpdateTodoRequest"
}
}
}
},
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Todo"
}
}
}
}
}
},
"delete": {
"operationId": "deleteTodo",
"summary": "Delete a todo",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"description": "No Content"
}
}
}
}
},
"components": {
"schemas": {
"Todo": {
"type": "object",
"required": ["id", "title", "completed"],
"properties": {
"id": {
"type": "string",
"description": "Unique identifier for the todo"
},
"title": {
"type": "string",
"description": "The todo item title"
},
"completed": {
"type": "boolean",
"description": "Whether the todo is completed",
"default": false
},
"description": {
"type": "string",
"description": "Optional description"
}
}
},
"CreateTodoRequest": {
"type": "object",
"required": ["title"],
"properties": {
"title": {
"type": "string",
"description": "The todo item title"
},
"description": {
"type": "string",
"description": "Optional description"
}
}
},
"UpdateTodoRequest": {
"type": "object",
"required": ["title", "completed"],
"properties": {
"title": {
"type": "string",
"description": "The todo item title"
},
"completed": {
"type": "boolean",
"description": "Whether the todo is completed"
},
"description": {
"type": "string",
"description": "Optional description"
}
}
}
}
}
});
// 2. Analyze the OpenAPI specification
println!("🔍 Analyzing OpenAPI specification...");
let mut analyzer = SchemaAnalyzer::new(spec)?;
let mut analysis = analyzer.analyze()?;
println!(" ✅ Found {} schemas", analysis.schemas.len());
println!(" ✅ Found {} operations", analysis.operations.len());
// 3. Configure the generator with retry and tracing
println!("\n⚙️ Configuring generator...");
let config = GeneratorConfig {
spec_path: PathBuf::from("todo-api.json"),
output_dir: PathBuf::from("examples/generated"),
module_name: "todo_api".to_string(),
enable_async_client: true,
enable_sse_client: false,
enable_specta: false,
retry_config: Some(openapi_to_rust::http_config::RetryConfig {
max_retries: 3,
initial_delay_ms: 500,
max_delay_ms: 16000,
}),
tracing_enabled: true,
..Default::default()
};
println!(" ✅ HTTP client enabled with:");
println!(" - Retry: max 3 retries with exponential backoff");
println!(" - Tracing: enabled for request/response logging");
// 4. Generate all files
println!("\n🏗️ Generating code...");
let generator = CodeGenerator::new(config);
let result = generator.generate_all(&mut analysis)?;
println!(" ✅ Generated {} files:", result.files.len() + 1);
for file in &result.files {
let path = file.path.display();
let lines = file.content.lines().count();
println!(" - {} ({} lines)", path, lines);
}
println!(
" - {} ({} lines)",
result.mod_file.path.display(),
result.mod_file.content.lines().count()
);
// 5. Show a preview of the generated client
println!("\n📄 Client preview:");
if let Some(client_file) = result
.files
.iter()
.find(|f| f.path.to_str() == Some("client.rs"))
{
// Show first 30 lines of the generated client
let preview_lines: Vec<&str> = client_file.content.lines().take(30).collect();
for line in preview_lines {
println!(" {}", line);
}
println!(
" ... ({} total lines)",
client_file.content.lines().count()
);
}
// 6. Save to disk
println!("\n💾 Saving files to disk...");
generator.write_files(&result)?;
println!(" ✅ Files written to: examples/generated/");
// 7. Show example usage
println!("\n📚 Example usage of the generated client:");
println!(
r#"
use todo_api::{{HttpClient, CreateTodoRequest}};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {{
// Create a client with retry and tracing
let client = HttpClient::new()
.with_base_url("https://api.example.com/v1")
.with_api_key("your-api-key");
// List all todos
let todos = client.list_todos().await?;
println!("Found {{}} todos", todos.len());
// Create a new todo
let new_todo = CreateTodoRequest {{
title: "Buy groceries".to_string(),
description: Some("Milk, eggs, bread".to_string()),
}};
let created = client.create_todo(new_todo).await?;
println!("Created todo: {{}}", created.id);
// Get a specific todo
let todo = client.get_todo(&created.id).await?;
println!("Todo: {{}} - completed: {{}}", todo.title, todo.completed);
// Update the todo
let update = UpdateTodoRequest {{
title: todo.title.clone(),
completed: true,
description: todo.description,
}};
let updated = client.update_todo(&created.id, update).await?;
println!("Updated todo completed status: {{}}", updated.completed);
// Delete the todo
client.delete_todo(&created.id).await?;
println!("Todo deleted");
Ok(())
}}
"#
);
println!("\n✨ Generation complete!");
println!("\n💡 Next steps:");
println!(" 1. Review the generated code in examples/generated/");
println!(" 2. Copy the generated files to your project");
println!(" 3. Add the required dependencies to your Cargo.toml:");
println!(" - reqwest = {{ version = \"0.12\", features = [\"json\"] }}");
println!(" - reqwest-middleware = \"0.3\"");
println!(" - reqwest-retry = \"0.6\"");
println!(" - reqwest-tracing = \"0.5\"");
println!(" - serde = {{ version = \"1.0\", features = [\"derive\"] }}");
println!(" - serde_json = \"1.0\"");
println!(" - thiserror = \"1.0\"");
println!(" - tokio = {{ version = \"1\", features = [\"full\"] }}");
Ok(())
}