1use crate::schema::Schema;
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct OpenApi {
10 pub openapi: String,
12 pub info: Info,
14 #[serde(default, skip_serializing_if = "Vec::is_empty")]
16 pub servers: Vec<Server>,
17 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
19 pub paths: HashMap<String, PathItem>,
20 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub components: Option<Components>,
23 #[serde(default, skip_serializing_if = "Vec::is_empty")]
25 pub tags: Vec<Tag>,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Info {
31 pub title: String,
33 pub version: String,
35 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub description: Option<String>,
38 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub terms_of_service: Option<String>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub contact: Option<Contact>,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub license: Option<License>,
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct Contact {
52 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub name: Option<String>,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub url: Option<String>,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub email: Option<String>,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct License {
66 pub name: String,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub url: Option<String>,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct Server {
76 pub url: String,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub description: Option<String>,
81}
82
83#[derive(Debug, Clone, Default, Serialize, Deserialize)]
85pub struct PathItem {
86 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub get: Option<Operation>,
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub post: Option<Operation>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub put: Option<Operation>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
97 pub delete: Option<Operation>,
98 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub patch: Option<Operation>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
103 pub options: Option<Operation>,
104 #[serde(default, skip_serializing_if = "Option::is_none")]
106 pub head: Option<Operation>,
107}
108
109#[derive(Debug, Clone, Default, Serialize, Deserialize)]
111pub struct Operation {
112 #[serde(
114 rename = "operationId",
115 default,
116 skip_serializing_if = "Option::is_none"
117 )]
118 pub operation_id: Option<String>,
119 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub summary: Option<String>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
124 pub description: Option<String>,
125 #[serde(default, skip_serializing_if = "Vec::is_empty")]
127 pub tags: Vec<String>,
128 #[serde(default, skip_serializing_if = "Vec::is_empty")]
130 pub parameters: Vec<Parameter>,
131 #[serde(
133 rename = "requestBody",
134 default,
135 skip_serializing_if = "Option::is_none"
136 )]
137 pub request_body: Option<RequestBody>,
138 pub responses: HashMap<String, Response>,
140 #[serde(default, skip_serializing_if = "Vec::is_empty")]
143 pub security: Vec<SecurityRequirement>,
144 #[serde(default, skip_serializing_if = "is_false")]
146 pub deprecated: bool,
147}
148
149fn is_false(b: &bool) -> bool {
150 !*b
151}
152
153fn default_responses() -> HashMap<String, Response> {
155 let mut responses = HashMap::new();
156 responses.insert(
157 "200".to_string(),
158 Response {
159 description: "Successful response".to_string(),
160 content: HashMap::new(),
161 },
162 );
163 responses
164}
165
166#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct Parameter {
169 pub name: String,
171 #[serde(rename = "in")]
173 pub location: ParameterLocation,
174 #[serde(default)]
176 pub required: bool,
177 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub schema: Option<Schema>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
182 pub title: Option<String>,
183 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub description: Option<String>,
186 #[serde(default, skip_serializing_if = "is_false")]
188 pub deprecated: bool,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub example: Option<serde_json::Value>,
192 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
194 pub examples: HashMap<String, Example>,
195}
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
199pub struct Example {
200 #[serde(default, skip_serializing_if = "Option::is_none")]
202 pub summary: Option<String>,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub description: Option<String>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub value: Option<serde_json::Value>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
211 pub external_value: Option<String>,
212}
213
214#[derive(Debug, Clone, Default)]
232pub struct ParamMeta {
233 pub title: Option<String>,
235 pub description: Option<String>,
237 pub deprecated: bool,
239 pub include_in_schema: bool,
241 pub example: Option<serde_json::Value>,
243 pub examples: HashMap<String, Example>,
245 pub ge: Option<f64>,
247 pub le: Option<f64>,
249 pub gt: Option<f64>,
251 pub lt: Option<f64>,
253 pub min_length: Option<usize>,
255 pub max_length: Option<usize>,
257 pub pattern: Option<String>,
259}
260
261impl ParamMeta {
262 #[must_use]
264 pub fn new() -> Self {
265 Self {
266 include_in_schema: true,
267 ..Default::default()
268 }
269 }
270
271 #[must_use]
273 pub fn title(mut self, title: impl Into<String>) -> Self {
274 self.title = Some(title.into());
275 self
276 }
277
278 #[must_use]
280 pub fn description(mut self, description: impl Into<String>) -> Self {
281 self.description = Some(description.into());
282 self
283 }
284
285 #[must_use]
287 pub fn deprecated(mut self) -> Self {
288 self.deprecated = true;
289 self
290 }
291
292 #[must_use]
294 pub fn exclude_from_schema(mut self) -> Self {
295 self.include_in_schema = false;
296 self
297 }
298
299 #[must_use]
301 pub fn example(mut self, example: serde_json::Value) -> Self {
302 self.example = Some(example);
303 self
304 }
305
306 #[must_use]
308 pub fn ge(mut self, value: f64) -> Self {
309 self.ge = Some(value);
310 self
311 }
312
313 #[must_use]
315 pub fn le(mut self, value: f64) -> Self {
316 self.le = Some(value);
317 self
318 }
319
320 #[must_use]
322 pub fn gt(mut self, value: f64) -> Self {
323 self.gt = Some(value);
324 self
325 }
326
327 #[must_use]
329 pub fn lt(mut self, value: f64) -> Self {
330 self.lt = Some(value);
331 self
332 }
333
334 #[must_use]
336 pub fn min_length(mut self, len: usize) -> Self {
337 self.min_length = Some(len);
338 self
339 }
340
341 #[must_use]
343 pub fn max_length(mut self, len: usize) -> Self {
344 self.max_length = Some(len);
345 self
346 }
347
348 #[must_use]
350 pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
351 self.pattern = Some(pattern.into());
352 self
353 }
354
355 #[must_use]
357 pub fn to_parameter(
358 &self,
359 name: impl Into<String>,
360 location: ParameterLocation,
361 required: bool,
362 schema: Option<Schema>,
363 ) -> Parameter {
364 Parameter {
365 name: name.into(),
366 location,
367 required,
368 schema,
369 title: self.title.clone(),
370 description: self.description.clone(),
371 deprecated: self.deprecated,
372 example: self.example.clone(),
373 examples: self.examples.clone(),
374 }
375 }
376}
377
378pub trait HasParamMeta {
382 fn param_meta() -> ParamMeta {
384 ParamMeta::new()
385 }
386}
387
388#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
390#[serde(rename_all = "lowercase")]
391pub enum ParameterLocation {
392 Path,
394 Query,
396 Header,
398 Cookie,
400}
401
402#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct RequestBody {
405 #[serde(default)]
407 pub required: bool,
408 pub content: HashMap<String, MediaType>,
410 #[serde(default, skip_serializing_if = "Option::is_none")]
412 pub description: Option<String>,
413}
414
415#[derive(Debug, Clone, Serialize, Deserialize)]
417pub struct MediaType {
418 #[serde(default, skip_serializing_if = "Option::is_none")]
420 pub schema: Option<Schema>,
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize)]
425pub struct Response {
426 pub description: String,
428 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
430 pub content: HashMap<String, MediaType>,
431}
432
433#[derive(Debug, Clone, Default, Serialize, Deserialize)]
435pub struct Components {
436 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
438 pub schemas: HashMap<String, Schema>,
439 #[serde(
441 rename = "securitySchemes",
442 default,
443 skip_serializing_if = "HashMap::is_empty"
444 )]
445 pub security_schemes: HashMap<String, SecurityScheme>,
446}
447
448pub type SecurityRequirement = HashMap<String, Vec<String>>;
454
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
457#[serde(rename_all = "lowercase")]
458pub enum ApiKeyLocation {
459 Header,
461 Query,
463 Cookie,
465}
466
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
469#[serde(tag = "type")]
470pub enum SecurityScheme {
471 #[serde(rename = "http")]
473 Http {
474 scheme: String,
476 #[serde(
478 rename = "bearerFormat",
479 default,
480 skip_serializing_if = "Option::is_none"
481 )]
482 bearer_format: Option<String>,
483 #[serde(default, skip_serializing_if = "Option::is_none")]
485 description: Option<String>,
486 },
487 #[serde(rename = "apiKey")]
489 ApiKey {
490 name: String,
492 #[serde(rename = "in")]
494 location: ApiKeyLocation,
495 #[serde(default, skip_serializing_if = "Option::is_none")]
497 description: Option<String>,
498 },
499 #[serde(rename = "oauth2")]
501 OAuth2 {
502 flows: OAuthFlows,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
506 description: Option<String>,
507 },
508}
509
510impl SecurityScheme {
511 #[must_use]
513 pub fn basic() -> Self {
514 Self::Http {
515 scheme: "basic".to_string(),
516 bearer_format: None,
517 description: None,
518 }
519 }
520
521 #[must_use]
523 pub fn bearer() -> Self {
524 Self::Http {
525 scheme: "bearer".to_string(),
526 bearer_format: None,
527 description: None,
528 }
529 }
530
531 #[must_use]
535 pub fn password(token_url: impl Into<String>) -> Self {
536 Self::OAuth2 {
537 flows: OAuthFlows {
538 password: OAuthPasswordFlow {
539 token_url: token_url.into(),
540 refresh_url: None,
541 scopes: HashMap::new(),
542 },
543 },
544 description: None,
545 }
546 }
547}
548
549#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
551pub struct OAuthFlows {
552 pub password: OAuthPasswordFlow,
554}
555
556#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
558pub struct OAuthPasswordFlow {
559 #[serde(rename = "tokenUrl")]
561 pub token_url: String,
562 #[serde(
564 rename = "refreshUrl",
565 default,
566 skip_serializing_if = "Option::is_none"
567 )]
568 pub refresh_url: Option<String>,
569 pub scopes: HashMap<String, String>,
571}
572
573#[derive(Debug, Clone, PartialEq, Eq)]
575pub struct SecurityMetadata {
576 pub name: String,
578 pub scheme: SecurityScheme,
580 pub scopes: Vec<String>,
582 pub required: bool,
584}
585
586impl SecurityMetadata {
587 #[must_use]
589 pub fn new(name: impl Into<String>, scheme: SecurityScheme) -> Self {
590 Self {
591 name: name.into(),
592 scheme,
593 scopes: Vec::new(),
594 required: true,
595 }
596 }
597}
598
599#[derive(Debug, Default)]
603pub struct SchemaRegistry {
604 schemas: HashMap<String, Schema>,
605}
606
607impl SchemaRegistry {
608 #[must_use]
610 pub fn new() -> Self {
611 Self {
612 schemas: HashMap::new(),
613 }
614 }
615
616 pub fn register(&mut self, name: impl Into<String>, schema: Schema) -> Schema {
620 let name = name.into();
621 self.schemas.entry(name.clone()).or_insert(schema);
622 Schema::reference(&name)
623 }
624
625 #[must_use]
627 pub fn into_schemas(self) -> HashMap<String, Schema> {
628 self.schemas
629 }
630}
631
632pub struct SchemaRegistryMut<'a> {
634 schemas: &'a mut HashMap<String, Schema>,
635}
636
637impl SchemaRegistryMut<'_> {
638 pub fn register(&mut self, name: impl Into<String>, schema: Schema) -> Schema {
640 let name = name.into();
641 self.schemas.entry(name.clone()).or_insert(schema);
642 Schema::reference(&name)
643 }
644}
645
646#[derive(Debug, Clone, Serialize, Deserialize)]
648pub struct Tag {
649 pub name: String,
651 #[serde(default, skip_serializing_if = "Option::is_none")]
653 pub description: Option<String>,
654}
655
656#[cfg(test)]
661mod param_meta_tests {
662 use super::*;
663
664 #[test]
665 fn new_creates_default_with_include_in_schema_true() {
666 let meta = ParamMeta::new();
667 assert!(meta.include_in_schema);
668 assert!(meta.title.is_none());
669 assert!(meta.description.is_none());
670 assert!(!meta.deprecated);
671 }
672
673 #[test]
674 fn title_sets_title() {
675 let meta = ParamMeta::new().title("User ID");
676 assert_eq!(meta.title.as_deref(), Some("User ID"));
677 }
678
679 #[test]
680 fn description_sets_description() {
681 let meta = ParamMeta::new().description("The unique identifier");
682 assert_eq!(meta.description.as_deref(), Some("The unique identifier"));
683 }
684
685 #[test]
686 fn deprecated_marks_as_deprecated() {
687 let meta = ParamMeta::new().deprecated();
688 assert!(meta.deprecated);
689 }
690
691 #[test]
692 fn exclude_from_schema_sets_include_false() {
693 let meta = ParamMeta::new().exclude_from_schema();
694 assert!(!meta.include_in_schema);
695 }
696
697 #[test]
698 fn example_sets_example_value() {
699 let meta = ParamMeta::new().example(serde_json::json!(42));
700 assert_eq!(meta.example, Some(serde_json::json!(42)));
701 }
702
703 #[test]
704 fn ge_sets_minimum_constraint() {
705 let meta = ParamMeta::new().ge(1.0);
706 assert_eq!(meta.ge, Some(1.0));
707 }
708
709 #[test]
710 fn le_sets_maximum_constraint() {
711 let meta = ParamMeta::new().le(100.0);
712 assert_eq!(meta.le, Some(100.0));
713 }
714
715 #[test]
716 fn gt_sets_exclusive_minimum() {
717 let meta = ParamMeta::new().gt(0.0);
718 assert_eq!(meta.gt, Some(0.0));
719 }
720
721 #[test]
722 fn lt_sets_exclusive_maximum() {
723 let meta = ParamMeta::new().lt(1000.0);
724 assert_eq!(meta.lt, Some(1000.0));
725 }
726
727 #[test]
728 fn min_length_sets_minimum_string_length() {
729 let meta = ParamMeta::new().min_length(3);
730 assert_eq!(meta.min_length, Some(3));
731 }
732
733 #[test]
734 fn max_length_sets_maximum_string_length() {
735 let meta = ParamMeta::new().max_length(255);
736 assert_eq!(meta.max_length, Some(255));
737 }
738
739 #[test]
740 fn pattern_sets_regex_constraint() {
741 let meta = ParamMeta::new().pattern(r"^\d{4}-\d{2}-\d{2}$");
742 assert_eq!(meta.pattern.as_deref(), Some(r"^\d{4}-\d{2}-\d{2}$"));
743 }
744
745 #[test]
746 fn builder_methods_chain() {
747 let meta = ParamMeta::new()
748 .title("Page")
749 .description("Page number for pagination")
750 .ge(1.0)
751 .le(1000.0)
752 .example(serde_json::json!(1));
753
754 assert_eq!(meta.title.as_deref(), Some("Page"));
755 assert_eq!(
756 meta.description.as_deref(),
757 Some("Page number for pagination")
758 );
759 assert_eq!(meta.ge, Some(1.0));
760 assert_eq!(meta.le, Some(1000.0));
761 assert_eq!(meta.example, Some(serde_json::json!(1)));
762 }
763
764 #[test]
765 fn to_parameter_creates_parameter_with_metadata() {
766 let meta = ParamMeta::new()
767 .title("User ID")
768 .description("Unique user identifier")
769 .deprecated()
770 .example(serde_json::json!(42));
771
772 let param = meta.to_parameter("user_id", ParameterLocation::Path, true, None);
773
774 assert_eq!(param.name, "user_id");
775 assert!(matches!(param.location, ParameterLocation::Path));
776 assert!(param.required);
777 assert_eq!(param.title.as_deref(), Some("User ID"));
778 assert_eq!(param.description.as_deref(), Some("Unique user identifier"));
779 assert!(param.deprecated);
780 assert_eq!(param.example, Some(serde_json::json!(42)));
781 }
782
783 #[test]
784 fn to_parameter_with_query_location() {
785 let meta = ParamMeta::new().description("Search query");
786 let param = meta.to_parameter("q", ParameterLocation::Query, false, None);
787
788 assert_eq!(param.name, "q");
789 assert!(matches!(param.location, ParameterLocation::Query));
790 assert!(!param.required);
791 }
792
793 #[test]
794 fn to_parameter_with_header_location() {
795 let meta = ParamMeta::new().description("API key");
796 let param = meta.to_parameter("X-API-Key", ParameterLocation::Header, true, None);
797
798 assert_eq!(param.name, "X-API-Key");
799 assert!(matches!(param.location, ParameterLocation::Header));
800 }
801
802 #[test]
803 fn to_parameter_with_cookie_location() {
804 let meta = ParamMeta::new().description("Session cookie");
805 let param = meta.to_parameter("session", ParameterLocation::Cookie, false, None);
806
807 assert_eq!(param.name, "session");
808 assert!(matches!(param.location, ParameterLocation::Cookie));
809 }
810
811 #[test]
812 fn default_param_meta_is_empty() {
813 let meta = ParamMeta::default();
814 assert!(meta.title.is_none());
815 assert!(meta.description.is_none());
816 assert!(!meta.deprecated);
817 assert!(!meta.include_in_schema); assert!(meta.example.is_none());
819 assert!(meta.ge.is_none());
820 assert!(meta.le.is_none());
821 assert!(meta.gt.is_none());
822 assert!(meta.lt.is_none());
823 assert!(meta.min_length.is_none());
824 assert!(meta.max_length.is_none());
825 assert!(meta.pattern.is_none());
826 }
827
828 #[test]
829 fn string_constraints_together() {
830 let meta = ParamMeta::new()
831 .min_length(1)
832 .max_length(100)
833 .pattern(r"^[a-zA-Z]+$");
834
835 assert_eq!(meta.min_length, Some(1));
836 assert_eq!(meta.max_length, Some(100));
837 assert_eq!(meta.pattern.as_deref(), Some(r"^[a-zA-Z]+$"));
838 }
839
840 #[test]
841 fn numeric_constraints_together() {
842 let meta = ParamMeta::new().gt(0.0).lt(100.0).ge(1.0).le(99.0);
843
844 assert_eq!(meta.gt, Some(0.0));
845 assert_eq!(meta.lt, Some(100.0));
846 assert_eq!(meta.ge, Some(1.0));
847 assert_eq!(meta.le, Some(99.0));
848 }
849}
850
851#[cfg(test)]
856mod serialization_tests {
857 use super::*;
858
859 #[test]
860 fn parameter_serializes_location_as_in() {
861 let param = Parameter {
862 name: "id".to_string(),
863 location: ParameterLocation::Path,
864 required: true,
865 schema: None,
866 title: None,
867 description: None,
868 deprecated: false,
869 example: None,
870 examples: HashMap::new(),
871 };
872
873 let json = serde_json::to_string(¶m).unwrap();
874 assert!(json.contains(r#""in":"path""#));
875 }
876
877 #[test]
878 fn parameter_location_serializes_lowercase() {
879 let path_json = serde_json::to_string(&ParameterLocation::Path).unwrap();
880 assert_eq!(path_json, r#""path""#);
881
882 let query_json = serde_json::to_string(&ParameterLocation::Query).unwrap();
883 assert_eq!(query_json, r#""query""#);
884
885 let header_json = serde_json::to_string(&ParameterLocation::Header).unwrap();
886 assert_eq!(header_json, r#""header""#);
887
888 let cookie_json = serde_json::to_string(&ParameterLocation::Cookie).unwrap();
889 assert_eq!(cookie_json, r#""cookie""#);
890 }
891
892 #[test]
893 fn parameter_skips_false_deprecated() {
894 let param = Parameter {
895 name: "id".to_string(),
896 location: ParameterLocation::Path,
897 required: true,
898 schema: None,
899 title: None,
900 description: None,
901 deprecated: false,
902 example: None,
903 examples: HashMap::new(),
904 };
905
906 let json = serde_json::to_string(¶m).unwrap();
907 assert!(!json.contains("deprecated"));
908 }
909
910 #[test]
911 fn parameter_includes_true_deprecated() {
912 let param = Parameter {
913 name: "old_id".to_string(),
914 location: ParameterLocation::Path,
915 required: true,
916 schema: None,
917 title: None,
918 description: Some("Deprecated, use new_id instead".to_string()),
919 deprecated: true,
920 example: None,
921 examples: HashMap::new(),
922 };
923
924 let json = serde_json::to_string(¶m).unwrap();
925 assert!(json.contains(r#""deprecated":true"#));
926 }
927
928 #[test]
929 fn openapi_builder_creates_valid_document() {
930 let doc = OpenApiBuilder::new("Test API", "1.0.0")
931 .description("A test API")
932 .server("https://api.example.com", Some("Production".to_string()))
933 .tag("users", Some("User operations".to_string()))
934 .build();
935
936 assert_eq!(doc.openapi, "3.1.0");
937 assert_eq!(doc.info.title, "Test API");
938 assert_eq!(doc.info.version, "1.0.0");
939 assert_eq!(doc.info.description.as_deref(), Some("A test API"));
940 assert_eq!(doc.servers.len(), 1);
941 assert_eq!(doc.servers[0].url, "https://api.example.com");
942 assert_eq!(doc.tags.len(), 1);
943 assert_eq!(doc.tags[0].name, "users");
944 }
945
946 #[test]
947 fn openapi_serializes_to_valid_json() {
948 let doc = OpenApiBuilder::new("Test API", "1.0.0").build();
949 let json = serde_json::to_string_pretty(&doc).unwrap();
950
951 assert!(json.contains(r#""openapi": "3.1.0""#));
952 assert!(json.contains(r#""title": "Test API""#));
953 assert!(json.contains(r#""version": "1.0.0""#));
954 }
955
956 #[test]
957 fn example_serializes_all_fields() {
958 let example = Example {
959 summary: Some("Example summary".to_string()),
960 description: Some("Example description".to_string()),
961 value: Some(serde_json::json!({"key": "value"})),
962 external_value: None,
963 };
964
965 let json = serde_json::to_string(&example).unwrap();
966 assert!(json.contains(r#""summary":"Example summary""#));
967 assert!(json.contains(r#""description":"Example description""#));
968 assert!(json.contains(r#""value""#));
969 }
970
971 #[test]
972 fn http_security_schemes_use_openapi_wire_names_and_round_trip() {
973 for (scheme, expected) in [
974 (
975 SecurityScheme::basic(),
976 serde_json::json!({"type": "http", "scheme": "basic"}),
977 ),
978 (
979 SecurityScheme::bearer(),
980 serde_json::json!({"type": "http", "scheme": "bearer"}),
981 ),
982 (
983 SecurityScheme::Http {
984 scheme: "bearer".to_string(),
985 bearer_format: Some("JWT".to_string()),
986 description: Some("Caller-supplied access token".to_string()),
987 },
988 serde_json::json!({
989 "type": "http",
990 "scheme": "bearer",
991 "bearerFormat": "JWT",
992 "description": "Caller-supplied access token"
993 }),
994 ),
995 ] {
996 let json = serde_json::to_value(&scheme).expect("HTTP scheme serialization");
997 assert_eq!(json, expected);
998 let decoded: SecurityScheme =
999 serde_json::from_value(json).expect("HTTP scheme deserialization");
1000 assert_eq!(decoded, scheme);
1001 }
1002 }
1003
1004 #[test]
1005 fn api_key_security_schemes_accept_only_header_query_and_cookie_locations() {
1006 for (location, wire_location) in [
1007 (ApiKeyLocation::Header, "header"),
1008 (ApiKeyLocation::Query, "query"),
1009 (ApiKeyLocation::Cookie, "cookie"),
1010 ] {
1011 let scheme = SecurityScheme::ApiKey {
1012 name: "api_key".to_string(),
1013 location,
1014 description: None,
1015 };
1016 let json = serde_json::to_value(&scheme).expect("API key scheme serialization");
1017 assert_eq!(
1018 json,
1019 serde_json::json!({"type": "apiKey", "name": "api_key", "in": wire_location})
1020 );
1021 let decoded: SecurityScheme =
1022 serde_json::from_value(json).expect("API key scheme deserialization");
1023 assert_eq!(decoded, scheme);
1024 }
1025 assert!(
1026 serde_json::from_value::<SecurityScheme>(serde_json::json!({
1027 "type": "apiKey", "name": "api_key", "in": "path"
1028 }))
1029 .is_err()
1030 );
1031 }
1032
1033 #[test]
1034 fn oauth_password_flow_retains_empty_scopes_and_required_token_url() {
1035 let scheme = SecurityScheme::password("/token");
1036 let json = serde_json::to_value(&scheme).expect("OAuth2 scheme serialization");
1037 assert_eq!(
1038 json,
1039 serde_json::json!({
1040 "type": "oauth2",
1041 "flows": {"password": {"tokenUrl": "/token", "scopes": {}}}
1042 })
1043 );
1044 let decoded: SecurityScheme =
1045 serde_json::from_value(json).expect("OAuth2 scheme deserialization");
1046 assert_eq!(decoded, scheme);
1047 for invalid in [
1048 serde_json::json!({"type": "oauth2", "flows": {"password": {"scopes": {}}}}),
1049 serde_json::json!({"type": "oauth2", "flows": {"password": {"tokenUrl": "/token"}}}),
1050 ] {
1051 assert!(serde_json::from_value::<SecurityScheme>(invalid).is_err());
1052 }
1053 }
1054
1055 #[test]
1056 fn oauth_password_flow_round_trips_scopes_refresh_url_and_description() {
1057 let scheme = SecurityScheme::OAuth2 {
1058 flows: OAuthFlows {
1059 password: OAuthPasswordFlow {
1060 token_url: "/auth/token".to_string(),
1061 refresh_url: Some("/auth/refresh".to_string()),
1062 scopes: HashMap::from([("read:items".to_string(), "Read items".to_string())]),
1063 },
1064 },
1065 description: Some("Item access".to_string()),
1066 };
1067 let json = serde_json::to_value(&scheme).expect("OAuth2 scheme serialization");
1068 assert_eq!(
1069 json,
1070 serde_json::json!({
1071 "type": "oauth2",
1072 "description": "Item access",
1073 "flows": {"password": {
1074 "tokenUrl": "/auth/token",
1075 "refreshUrl": "/auth/refresh",
1076 "scopes": {"read:items": "Read items"}
1077 }}
1078 })
1079 );
1080 let decoded: SecurityScheme =
1081 serde_json::from_value(json).expect("OAuth2 scheme deserialization");
1082 assert_eq!(decoded, scheme);
1083 }
1084
1085 #[test]
1086 fn operation_security_preserves_conjunctions_alternatives_and_anonymous_access() {
1087 let operation = Operation {
1088 security: vec![
1089 HashMap::from([
1090 ("AccessToken".to_string(), Vec::new()),
1091 ("ApiKey".to_string(), Vec::new()),
1092 ]),
1093 HashMap::from([("PasswordAuth".to_string(), vec!["read:items".to_string()])]),
1094 HashMap::new(),
1095 ],
1096 ..Default::default()
1097 };
1098 let json = serde_json::to_value(&operation).expect("operation serialization");
1099 assert_eq!(
1100 json["security"],
1101 serde_json::json!([
1102 {"AccessToken": [], "ApiKey": []},
1103 {"PasswordAuth": ["read:items"]},
1104 {}
1105 ])
1106 );
1107 let decoded: Operation = serde_json::from_value(json).expect("operation deserialization");
1108 assert_eq!(decoded.security, operation.security);
1109 let unprotected = serde_json::to_value(Operation::default()).expect("default operation");
1110 assert!(unprotected.get("security").is_none());
1111 }
1112
1113 #[test]
1114 fn scheme_only_components_survive_build_and_round_trip() {
1115 let document = OpenApiBuilder::new("Security API", "1")
1116 .security_scheme("AccessToken", SecurityScheme::bearer())
1117 .build();
1118 let components = document
1119 .components
1120 .as_ref()
1121 .expect("scheme-only components");
1122 assert!(components.schemas.is_empty());
1123 assert_eq!(components.security_schemes.len(), 1);
1124 let json = serde_json::to_value(&document).expect("document serialization");
1125 assert_eq!(
1126 json["components"]["securitySchemes"]["AccessToken"],
1127 serde_json::json!({"type": "http", "scheme": "bearer"})
1128 );
1129 assert!(json["components"].get("schemas").is_none());
1130 assert!(json["components"].get("security_schemes").is_none());
1131 let decoded: OpenApi = serde_json::from_value(json).expect("document deserialization");
1132 assert_eq!(
1133 decoded
1134 .components
1135 .expect("decoded components")
1136 .security_schemes,
1137 components.security_schemes
1138 );
1139 assert!(
1140 OpenApiBuilder::new("Public API", "1")
1141 .build()
1142 .components
1143 .is_none()
1144 );
1145 }
1146
1147 #[test]
1148 fn duplicate_identical_security_schemes_preserve_existing_schema_components() {
1149 let document = OpenApiBuilder::new("Security API", "1")
1150 .schema("Item", Schema::integer(Some("int64")))
1151 .security_scheme("AccessToken", SecurityScheme::bearer())
1152 .security_scheme("AccessToken", SecurityScheme::bearer())
1153 .build();
1154 let components = document.components.expect("schema and security components");
1155 assert_eq!(components.schemas.len(), 1);
1156 assert!(components.schemas.contains_key("Item"));
1157 assert_eq!(components.security_schemes.len(), 1);
1158 assert_eq!(
1159 components.security_schemes["AccessToken"],
1160 SecurityScheme::bearer()
1161 );
1162 }
1163
1164 #[test]
1165 #[should_panic(expected = "conflicting security scheme definition for 'AccessToken'")]
1166 fn conflicting_security_scheme_definitions_are_rejected() {
1167 let _builder = OpenApiBuilder::new("Security API", "1")
1168 .security_scheme("AccessToken", SecurityScheme::bearer())
1169 .security_scheme("AccessToken", SecurityScheme::basic());
1170 }
1171
1172 #[test]
1173 fn route_security_preserves_manual_alternatives_and_scopes() {
1174 let route = fastapi_router::Route::new(fastapi_types::Method::Get, "/protected")
1175 .security("PasswordAuth", ["read:items"])
1176 .security_scheme("ApiKey");
1177 let mut builder = OpenApiBuilder::new("Security API", "1")
1178 .security_scheme(
1179 "PasswordAuth",
1180 SecurityScheme::OAuth2 {
1181 flows: OAuthFlows {
1182 password: OAuthPasswordFlow {
1183 token_url: "/token".to_string(),
1184 refresh_url: None,
1185 scopes: HashMap::from([(
1186 "read:items".to_string(),
1187 "Read items".to_string(),
1188 )]),
1189 },
1190 },
1191 description: None,
1192 },
1193 )
1194 .security_scheme(
1195 "ApiKey",
1196 SecurityScheme::ApiKey {
1197 name: "X-Api-Key".to_string(),
1198 location: ApiKeyLocation::Header,
1199 description: None,
1200 },
1201 );
1202 let operation = builder.add_route(&route).expect("GET operation");
1203 assert_eq!(operation.security.len(), 2);
1204 assert_eq!(operation.security[0].len(), 1);
1205 assert_eq!(operation.security[0]["PasswordAuth"], ["read:items"]);
1206 assert_eq!(operation.security[1].len(), 1);
1207 assert!(operation.security[1]["ApiKey"].is_empty());
1208 let json = serde_json::to_value(builder.build()).expect("secured document");
1209 assert_eq!(
1210 json["paths"]["/protected"]["get"]["security"],
1211 serde_json::json!([{"PasswordAuth": ["read:items"]}, {"ApiKey": []}])
1212 );
1213 }
1214
1215 #[test]
1216 #[should_panic(
1217 expected = "security requirement 'MissingScheme' has no registered security scheme"
1218 )]
1219 fn build_rejects_unregistered_manual_security_requirement_names() {
1220 let route = fastapi_router::Route::new(fastapi_types::Method::Get, "/protected")
1221 .security_scheme("MissingScheme");
1222 let mut builder = OpenApiBuilder::new("Security API", "1");
1223 builder.add_route(&route).expect("GET operation");
1224 let _document = builder.build();
1225 }
1226}
1227
1228pub struct OpenApiBuilder {
1230 info: Info,
1231 servers: Vec<Server>,
1232 paths: HashMap<String, PathItem>,
1233 components: Components,
1234 tags: Vec<Tag>,
1235}
1236
1237impl OpenApiBuilder {
1238 #[must_use]
1240 pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
1241 Self {
1242 info: Info {
1243 title: title.into(),
1244 version: version.into(),
1245 description: None,
1246 terms_of_service: None,
1247 contact: None,
1248 license: None,
1249 },
1250 servers: Vec::new(),
1251 paths: HashMap::new(),
1252 components: Components::default(),
1253 tags: Vec::new(),
1254 }
1255 }
1256
1257 #[must_use]
1259 pub fn description(mut self, description: impl Into<String>) -> Self {
1260 self.info.description = Some(description.into());
1261 self
1262 }
1263
1264 #[must_use]
1266 pub fn server(mut self, url: impl Into<String>, description: Option<String>) -> Self {
1267 self.servers.push(Server {
1268 url: url.into(),
1269 description,
1270 });
1271 self
1272 }
1273
1274 #[must_use]
1276 pub fn tag(mut self, name: impl Into<String>, description: Option<String>) -> Self {
1277 self.tags.push(Tag {
1278 name: name.into(),
1279 description,
1280 });
1281 self
1282 }
1283
1284 #[must_use]
1286 pub fn schema(mut self, name: impl Into<String>, schema: Schema) -> Self {
1287 self.components.schemas.insert(name.into(), schema);
1288 self
1289 }
1290
1291 #[must_use]
1299 pub fn security_scheme(mut self, name: impl Into<String>, scheme: SecurityScheme) -> Self {
1300 match self.components.security_schemes.entry(name.into()) {
1301 std::collections::hash_map::Entry::Vacant(entry) => {
1302 entry.insert(scheme);
1303 }
1304 std::collections::hash_map::Entry::Occupied(entry) => {
1305 assert_eq!(
1306 entry.get(),
1307 &scheme,
1308 "conflicting security scheme definition for '{}'",
1309 entry.key()
1310 );
1311 }
1312 }
1313 self
1314 }
1315
1316 pub fn registry(&mut self) -> SchemaRegistryMut<'_> {
1318 SchemaRegistryMut {
1319 schemas: &mut self.components.schemas,
1320 }
1321 }
1322
1323 #[allow(clippy::too_many_lines)]
1327 pub fn add_route(&mut self, route: &fastapi_router::Route) -> Option<&mut Operation> {
1328 use fastapi_router::Converter as RouteConverter;
1329
1330 fn param_schema(conv: RouteConverter) -> Schema {
1331 match conv {
1332 RouteConverter::Str | RouteConverter::Path => Schema::string(),
1333 RouteConverter::Int => Schema::integer(Some("int64")),
1334 RouteConverter::Float => Schema::number(Some("double")),
1335 RouteConverter::Uuid => Schema::Primitive(crate::schema::PrimitiveSchema {
1336 schema_type: crate::schema::SchemaType::String,
1337 format: Some("uuid".to_string()),
1338 nullable: false,
1339 }),
1340 }
1341 }
1342
1343 let mut op = Operation {
1344 operation_id: if route.operation_id.is_empty() {
1345 None
1346 } else {
1347 Some(route.operation_id.clone())
1348 },
1349 summary: route.summary.clone(),
1350 description: route.description.clone(),
1351 tags: route.tags.clone(),
1352 deprecated: route.deprecated,
1353 security: route
1354 .security
1355 .iter()
1356 .map(|requirement| {
1357 HashMap::from([(requirement.scheme.clone(), requirement.scopes.clone())])
1358 })
1359 .collect(),
1360 ..Default::default()
1361 };
1362
1363 for p in &route.path_params {
1365 let mut examples = HashMap::new();
1366 for (name, value) in &p.examples {
1367 examples.insert(
1368 name.clone(),
1369 Example {
1370 summary: None,
1371 description: None,
1372 value: Some(value.clone()),
1373 external_value: None,
1374 },
1375 );
1376 }
1377
1378 op.parameters.push(Parameter {
1379 name: p.name.clone(),
1380 location: ParameterLocation::Path,
1381 required: true,
1382 schema: Some(param_schema(p.converter)),
1383 title: p.title.clone(),
1384 description: p.description.clone(),
1385 deprecated: p.deprecated,
1386 example: p.example.clone(),
1387 examples,
1388 });
1389 }
1390
1391 if let Some(schema_name) = &route.request_body_schema {
1393 let content_type = route
1394 .request_body_content_type
1395 .clone()
1396 .unwrap_or_else(|| "application/json".to_string());
1397 let mut content = HashMap::new();
1398 content.insert(
1399 content_type,
1400 MediaType {
1401 schema: Some(Schema::reference(schema_name)),
1402 },
1403 );
1404 op.request_body = Some(RequestBody {
1405 required: route.request_body_required,
1406 content,
1407 description: None,
1408 });
1409 }
1410
1411 let mut responses = HashMap::new();
1413 if route.responses.is_empty() {
1414 responses = default_responses();
1415 } else {
1416 for r in &route.responses {
1417 let mut content = HashMap::new();
1418 content.insert(
1419 "application/json".to_string(),
1420 MediaType {
1421 schema: Some(Schema::reference(&r.schema_name)),
1422 },
1423 );
1424 responses.insert(
1425 r.status.to_string(),
1426 Response {
1427 description: r.description.clone(),
1428 content,
1429 },
1430 );
1431 }
1432 }
1433 op.responses = responses;
1434
1435 let mut path = route.path.clone();
1437 for parameter in &route.path_params {
1438 path = path.replace(
1439 &format!("{{*{}}}", parameter.name),
1440 &format!("{{{}}}", parameter.name),
1441 );
1442 if let Some(start) = path.find(&format!("{{{}:", parameter.name))
1443 && let Some(end) = path[start..].find('}')
1444 {
1445 path.replace_range(start..=start + end, &format!("{{{}}}", parameter.name));
1446 }
1447 }
1448 let path_item = self.paths.entry(path).or_default();
1449 let slot = match route.method.as_str() {
1450 "GET" => &mut path_item.get,
1451 "POST" => &mut path_item.post,
1452 "PUT" => &mut path_item.put,
1453 "DELETE" => &mut path_item.delete,
1454 "PATCH" => &mut path_item.patch,
1455 "OPTIONS" => &mut path_item.options,
1456 "HEAD" => &mut path_item.head,
1457 _ => return None,
1458 };
1459 Some(slot.insert(op))
1460 }
1461
1462 pub fn add_routes<'a, I>(&mut self, routes: I)
1464 where
1465 I: IntoIterator<Item = &'a fastapi_router::Route>,
1466 {
1467 for r in routes {
1468 self.add_route(r);
1469 }
1470 }
1471
1472 #[must_use]
1493 pub fn operation(
1494 mut self,
1495 method: &str,
1496 path: impl Into<String>,
1497 operation: Operation,
1498 ) -> Self {
1499 let path = path.into();
1500 let path_item = self.paths.entry(path).or_default();
1501
1502 match method.to_uppercase().as_str() {
1503 "GET" => path_item.get = Some(operation),
1504 "POST" => path_item.post = Some(operation),
1505 "PUT" => path_item.put = Some(operation),
1506 "DELETE" => path_item.delete = Some(operation),
1507 "PATCH" => path_item.patch = Some(operation),
1508 "OPTIONS" => path_item.options = Some(operation),
1509 "HEAD" => path_item.head = Some(operation),
1510 _ => {} }
1512
1513 self
1514 }
1515
1516 #[must_use]
1518 pub fn get(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
1519 let operation_id = operation_id.into();
1520 self.operation(
1521 "GET",
1522 path,
1523 Operation {
1524 operation_id: if operation_id.is_empty() {
1525 None
1526 } else {
1527 Some(operation_id)
1528 },
1529 responses: default_responses(),
1530 ..Default::default()
1531 },
1532 )
1533 }
1534
1535 #[must_use]
1537 pub fn post(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
1538 let operation_id = operation_id.into();
1539 self.operation(
1540 "POST",
1541 path,
1542 Operation {
1543 operation_id: if operation_id.is_empty() {
1544 None
1545 } else {
1546 Some(operation_id)
1547 },
1548 responses: default_responses(),
1549 ..Default::default()
1550 },
1551 )
1552 }
1553
1554 #[must_use]
1556 pub fn put(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
1557 let operation_id = operation_id.into();
1558 self.operation(
1559 "PUT",
1560 path,
1561 Operation {
1562 operation_id: if operation_id.is_empty() {
1563 None
1564 } else {
1565 Some(operation_id)
1566 },
1567 responses: default_responses(),
1568 ..Default::default()
1569 },
1570 )
1571 }
1572
1573 #[must_use]
1575 pub fn delete(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
1576 let operation_id = operation_id.into();
1577 self.operation(
1578 "DELETE",
1579 path,
1580 Operation {
1581 operation_id: if operation_id.is_empty() {
1582 None
1583 } else {
1584 Some(operation_id)
1585 },
1586 responses: default_responses(),
1587 ..Default::default()
1588 },
1589 )
1590 }
1591
1592 #[must_use]
1594 pub fn patch(self, path: impl Into<String>, operation_id: impl Into<String>) -> Self {
1595 let operation_id = operation_id.into();
1596 self.operation(
1597 "PATCH",
1598 path,
1599 Operation {
1600 operation_id: if operation_id.is_empty() {
1601 None
1602 } else {
1603 Some(operation_id)
1604 },
1605 responses: default_responses(),
1606 ..Default::default()
1607 },
1608 )
1609 }
1610
1611 #[must_use]
1617 pub fn build(self) -> OpenApi {
1618 for item in self.paths.values() {
1619 for operation in [
1620 &item.get,
1621 &item.post,
1622 &item.put,
1623 &item.delete,
1624 &item.patch,
1625 &item.options,
1626 &item.head,
1627 ]
1628 .into_iter()
1629 .flatten()
1630 {
1631 for requirement in &operation.security {
1632 for name in requirement.keys() {
1633 assert!(
1634 self.components.security_schemes.contains_key(name),
1635 "security requirement '{}' has no registered security scheme",
1636 name
1637 );
1638 }
1639 }
1640 }
1641 }
1642 OpenApi {
1643 openapi: "3.1.0".to_string(),
1644 info: self.info,
1645 servers: self.servers,
1646 paths: self.paths,
1647 components: if self.components.schemas.is_empty()
1648 && self.components.security_schemes.is_empty()
1649 {
1650 None
1651 } else {
1652 Some(self.components)
1653 },
1654 tags: self.tags,
1655 }
1656 }
1657}