armature-openapi 0.2.1

OpenAPI specification generation for Armature APIs
Documentation
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Builder for creating OpenAPI specifications programmatically

use crate::spec::*;
use std::collections::HashMap;

/// Builder for OpenAPI specifications
#[derive(Debug, Clone)]
pub struct OpenApiBuilder {
    spec: OpenApiSpec,
}

impl OpenApiBuilder {
    /// Create a new OpenAPI builder
    pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            spec: OpenApiSpec {
                openapi: "3.0.0".to_string(),
                info: Info {
                    title: title.into(),
                    version: version.into(),
                    description: None,
                    terms_of_service: None,
                    contact: None,
                    license: None,
                },
                servers: Vec::new(),
                paths: HashMap::new(),
                components: Some(Components::default()),
                security: Vec::new(),
                tags: Vec::new(),
            },
        }
    }

    /// Set description
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.spec.info.description = Some(description.into());
        self
    }

    /// Set terms of service
    pub fn terms_of_service(mut self, terms: impl Into<String>) -> Self {
        self.spec.info.terms_of_service = Some(terms.into());
        self
    }

    /// Add contact information
    pub fn contact(
        mut self,
        name: Option<String>,
        url: Option<String>,
        email: Option<String>,
    ) -> Self {
        self.spec.info.contact = Some(Contact { name, url, email });
        self
    }

    /// Add license
    pub fn license(mut self, name: impl Into<String>, url: Option<String>) -> Self {
        self.spec.info.license = Some(License {
            name: name.into(),
            url,
        });
        self
    }

    /// Add a server
    pub fn server(mut self, url: impl Into<String>, description: Option<String>) -> Self {
        self.spec.servers.push(Server {
            url: url.into(),
            description,
        });
        self
    }

    /// Add a tag
    pub fn tag(mut self, name: impl Into<String>, description: Option<String>) -> Self {
        self.spec.tags.push(Tag {
            name: name.into(),
            description,
        });
        self
    }

    /// Add a path
    pub fn path(mut self, path: impl Into<String>, item: PathItem) -> Self {
        self.spec.paths.insert(path.into(), item);
        self
    }

    /// Add a schema component
    pub fn schema(mut self, name: impl Into<String>, schema: Schema) -> Self {
        if let Some(ref mut components) = self.spec.components {
            components.schemas.insert(name.into(), schema);
        }
        self
    }

    /// Add a security scheme
    pub fn security_scheme(mut self, name: impl Into<String>, scheme: SecurityScheme) -> Self {
        if let Some(ref mut components) = self.spec.components {
            components.security_schemes.insert(name.into(), scheme);
        }
        self
    }

    /// Add global security requirement
    pub fn security(mut self, requirement: SecurityRequirement) -> Self {
        self.spec.security.push(requirement);
        self
    }

    /// Build the OpenAPI specification
    pub fn build(self) -> OpenApiSpec {
        self.spec
    }
}

/// Helper functions for creating common components
impl OpenApiBuilder {
    /// Add Bearer JWT authentication
    pub fn add_bearer_auth(self, name: impl Into<String>) -> Self {
        self.security_scheme(
            name,
            SecurityScheme::Http {
                scheme: "bearer".to_string(),
                bearer_format: Some("JWT".to_string()),
            },
        )
    }

    /// Add API key authentication
    pub fn add_api_key_auth(
        self,
        name: impl Into<String>,
        key_name: impl Into<String>,
        location: ApiKeyLocation,
    ) -> Self {
        self.security_scheme(
            name,
            SecurityScheme::ApiKey {
                name: key_name.into(),
                location,
            },
        )
    }

    /// Add OpenID Connect authentication
    pub fn add_openid_connect_auth(
        self,
        name: impl Into<String>,
        open_id_connect_url: impl Into<String>,
    ) -> Self {
        self.security_scheme(
            name,
            SecurityScheme::OpenIdConnect {
                open_id_connect_url: open_id_connect_url.into(),
            },
        )
    }
}

/// Builder for path items
pub struct PathItemBuilder {
    item: PathItem,
}

impl PathItemBuilder {
    pub fn new() -> Self {
        Self {
            item: PathItem::default(),
        }
    }

    pub fn get(mut self, operation: Operation) -> Self {
        self.item.get = Some(operation);
        self
    }

    pub fn post(mut self, operation: Operation) -> Self {
        self.item.post = Some(operation);
        self
    }

    pub fn put(mut self, operation: Operation) -> Self {
        self.item.put = Some(operation);
        self
    }

    pub fn delete(mut self, operation: Operation) -> Self {
        self.item.delete = Some(operation);
        self
    }

    pub fn patch(mut self, operation: Operation) -> Self {
        self.item.patch = Some(operation);
        self
    }

    pub fn build(self) -> PathItem {
        self.item
    }
}

impl Default for PathItemBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Builder for operations
pub struct OperationBuilder {
    operation: Operation,
}

impl OperationBuilder {
    pub fn new() -> Self {
        Self {
            operation: Operation::default(),
        }
    }

    pub fn summary(mut self, summary: impl Into<String>) -> Self {
        self.operation.summary = Some(summary.into());
        self
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.operation.description = Some(description.into());
        self
    }

    pub fn operation_id(mut self, id: impl Into<String>) -> Self {
        self.operation.operation_id = Some(id.into());
        self
    }

    pub fn tag(mut self, tag: impl Into<String>) -> Self {
        self.operation.tags.push(tag.into());
        self
    }

    pub fn parameter(mut self, parameter: Parameter) -> Self {
        self.operation.parameters.push(parameter);
        self
    }

    pub fn request_body(mut self, body: RequestBody) -> Self {
        self.operation.request_body = Some(body);
        self
    }

    pub fn response(mut self, status: impl Into<String>, response: Response) -> Self {
        self.operation.responses.insert(status.into(), response);
        self
    }

    pub fn security(mut self, requirement: SecurityRequirement) -> Self {
        self.operation.security.push(requirement);
        self
    }

    pub fn build(self) -> Operation {
        self.operation
    }
}

impl Default for OperationBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Helper functions for creating schemas
pub fn string_schema() -> Schema {
    Schema {
        schema_type: Some("string".to_string()),
        ..Default::default()
    }
}

pub fn integer_schema() -> Schema {
    Schema {
        schema_type: Some("integer".to_string()),
        format: Some("int64".to_string()),
        ..Default::default()
    }
}

pub fn number_schema() -> Schema {
    Schema {
        schema_type: Some("number".to_string()),
        format: Some("double".to_string()),
        ..Default::default()
    }
}

pub fn boolean_schema() -> Schema {
    Schema {
        schema_type: Some("boolean".to_string()),
        ..Default::default()
    }
}

pub fn array_schema(items: Schema) -> Schema {
    Schema {
        schema_type: Some("array".to_string()),
        items: Some(Box::new(items)),
        ..Default::default()
    }
}

pub fn object_schema(properties: HashMap<String, Schema>, required: Vec<String>) -> Schema {
    Schema {
        schema_type: Some("object".to_string()),
        properties: Some(properties),
        required,
        ..Default::default()
    }
}

pub fn ref_schema(reference: impl Into<String>) -> Schema {
    Schema {
        reference: Some(format!("#/components/schemas/{}", reference.into())),
        ..Default::default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_openapi_builder_basic() {
        let spec = OpenApiBuilder::new("Test API", "1.0.0").build();

        assert_eq!(spec.info.title, "Test API");
        assert_eq!(spec.info.version, "1.0.0");
        assert_eq!(spec.openapi, "3.0.0");
    }

    #[test]
    fn test_openapi_builder_with_description() {
        let spec = OpenApiBuilder::new("Test API", "1.0.0")
            .description("A test API")
            .build();

        assert_eq!(spec.info.description, Some("A test API".to_string()));
    }

    #[test]
    fn test_operation_builder_basic() {
        let operation = OperationBuilder::new()
            .summary("Get user")
            .description("Get a user by ID")
            .operation_id("getUser")
            .build();

        assert_eq!(operation.summary, Some("Get user".to_string()));
        assert_eq!(operation.description, Some("Get a user by ID".to_string()));
        assert_eq!(operation.operation_id, Some("getUser".to_string()));
    }

    #[test]
    fn test_operation_builder_with_tag() {
        let operation = OperationBuilder::new().tag("users").tag("admin").build();

        assert_eq!(operation.tags.len(), 2);
        assert!(operation.tags.contains(&"users".to_string()));
        assert!(operation.tags.contains(&"admin".to_string()));
    }

    #[test]
    fn test_string_schema() {
        let schema = string_schema();
        assert_eq!(schema.schema_type, Some("string".to_string()));
    }

    #[test]
    fn test_integer_schema() {
        let schema = integer_schema();
        assert_eq!(schema.schema_type, Some("integer".to_string()));
        assert_eq!(schema.format, Some("int64".to_string()));
    }

    #[test]
    fn test_number_schema() {
        let schema = number_schema();
        assert_eq!(schema.schema_type, Some("number".to_string()));
        assert_eq!(schema.format, Some("double".to_string()));
    }

    #[test]
    fn test_boolean_schema() {
        let schema = boolean_schema();
        assert_eq!(schema.schema_type, Some("boolean".to_string()));
    }

    #[test]
    fn test_array_schema() {
        let items = string_schema();
        let schema = array_schema(items);

        assert_eq!(schema.schema_type, Some("array".to_string()));
        assert!(schema.items.is_some());
    }

    #[test]
    fn test_object_schema() {
        let mut properties = HashMap::new();
        properties.insert("name".to_string(), string_schema());
        properties.insert("age".to_string(), integer_schema());

        let required = vec!["name".to_string()];
        let schema = object_schema(properties, required);

        assert_eq!(schema.schema_type, Some("object".to_string()));
        assert_eq!(schema.properties.as_ref().unwrap().len(), 2);
        assert_eq!(schema.required.len(), 1);
    }

    #[test]
    fn test_ref_schema() {
        let schema = ref_schema("User");
        assert_eq!(
            schema.reference,
            Some("#/components/schemas/User".to_string())
        );
    }

    #[test]
    fn test_operation_builder_default() {
        let builder = OperationBuilder::default();
        let operation = builder.build();
        assert!(operation.summary.is_none());
    }

    #[test]
    fn test_add_openid_connect_auth() {
        let spec = OpenApiBuilder::new("Test API", "1.0.0")
            .add_openid_connect_auth(
                "oidc",
                "https://example.com/.well-known/openid-configuration",
            )
            .build();

        let components = spec.components.unwrap();
        match components.security_schemes.get("oidc").unwrap() {
            SecurityScheme::OpenIdConnect {
                open_id_connect_url,
            } => {
                assert_eq!(
                    open_id_connect_url,
                    "https://example.com/.well-known/openid-configuration"
                );
            }
            _ => panic!("expected OpenIdConnect variant"),
        }
    }
}