1#![cfg_attr(feature = "docs", doc = "## Feature flags")]
7#![cfg_attr(feature = "docs", doc = document_features::document_features!())]
8#![cfg_attr(docsrs, feature(doc_cfg))]
21#![cfg_attr(all(test, coverage_nightly), feature(coverage_attribute))]
22#![deny(missing_docs)]
23#![deny(unsafe_code)]
24#![deny(unreachable_pub)]
25#![deny(clippy::mod_module_files)]
26
27use std::fmt::Formatter;
28
29use indexmap::IndexMap;
30use serde::de::{Error, Expected, Visitor};
31use serde::{Deserializer, Serializer};
32use serde_derive::{Deserialize, Serialize};
33
34pub use self::content::{Content, ContentBuilder};
35pub use self::external_docs::ExternalDocs;
36pub use self::header::{Header, HeaderBuilder};
37pub use self::info::{Contact, ContactBuilder, Info, InfoBuilder, License, LicenseBuilder};
38pub use self::path::{HttpMethod, PathItem, Paths, PathsBuilder};
39pub use self::response::{Response, ResponseBuilder, Responses, ResponsesBuilder};
40pub use self::schema::{Components, ComponentsBuilder, Discriminator, Object, Ref, Schema, Type};
41pub use self::security::SecurityRequirement;
42pub use self::server::{Server, ServerBuilder, ServerVariable, ServerVariableBuilder};
43pub use self::tag::Tag;
44
45pub mod content;
46pub mod encoding;
47pub mod example;
48pub mod extensions;
49pub mod external_docs;
50pub mod header;
51pub mod info;
52pub mod link;
53pub mod path;
54pub mod request_body;
55pub mod response;
56pub mod schema;
57pub mod security;
58pub mod server;
59pub mod tag;
60pub mod xml;
61
62#[non_exhaustive]
71#[derive(
72 serde_derive::Serialize, serde_derive::Deserialize, Default, Clone, PartialEq, bon::Builder,
73)]
74#[cfg_attr(feature = "debug", derive(Debug))]
75#[serde(rename_all = "camelCase")]
76#[builder(on(_, into))]
77pub struct OpenApi {
78 #[builder(default)]
80 pub openapi: OpenApiVersion,
81
82 #[builder(default)]
86 pub info: Info,
87
88 #[serde(skip_serializing_if = "Option::is_none")]
94 pub servers: Option<Vec<Server>>,
95
96 #[builder(default)]
100 pub paths: Paths,
101
102 #[serde(skip_serializing_if = "Option::is_none")]
108 pub components: Option<Components>,
109
110 #[serde(skip_serializing_if = "Option::is_none")]
116 pub security: Option<Vec<SecurityRequirement>>,
117
118 #[serde(skip_serializing_if = "Option::is_none")]
122 pub tags: Option<Vec<Tag>>,
123
124 #[serde(skip_serializing_if = "Option::is_none")]
128 pub external_docs: Option<ExternalDocs>,
129
130 #[serde(rename = "$schema", default, skip_serializing_if = "String::is_empty")]
135 #[builder(default)]
136 pub schema: String,
137
138 #[serde(skip_serializing_if = "Option::is_none", flatten)]
140 pub extensions: Option<Extensions>,
141}
142
143impl OpenApi {
144 pub fn new(info: impl Into<Info>, paths: impl Into<Paths>) -> Self {
157 Self {
158 info: info.into(),
159 paths: paths.into(),
160 ..Default::default()
161 }
162 }
163
164 pub fn to_json(&self) -> Result<String, serde_json::Error> {
166 serde_json::to_string(self)
167 }
168
169 pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
171 serde_json::to_string_pretty(self)
172 }
173
174 #[cfg(feature = "yaml")]
176 #[cfg_attr(docsrs, doc(cfg(feature = "yaml")))]
177 pub fn to_yaml(&self) -> Result<String, serde_norway::Error> {
178 serde_norway::to_string(self)
179 }
180
181 pub fn merge_from(mut self, other: OpenApi) -> OpenApi {
186 self.merge(other);
187 self
188 }
189
190 pub fn merge(&mut self, mut other: OpenApi) {
205 if let Some(other_servers) = &mut other.servers {
206 let servers = self.servers.get_or_insert(Vec::new());
207 other_servers.retain(|server| !servers.contains(server));
208 servers.append(other_servers);
209 }
210
211 if !other.paths.paths.is_empty() {
212 self.paths.merge(other.paths);
213 };
214
215 if let Some(other_components) = &mut other.components {
216 let components = self.components.get_or_insert(Components::default());
217
218 other_components
219 .schemas
220 .retain(|name, _| !components.schemas.contains_key(name));
221 components.schemas.append(&mut other_components.schemas);
222
223 other_components
224 .responses
225 .retain(|name, _| !components.responses.contains_key(name));
226 components.responses.append(&mut other_components.responses);
227
228 other_components
229 .security_schemes
230 .retain(|name, _| !components.security_schemes.contains_key(name));
231 components
232 .security_schemes
233 .append(&mut other_components.security_schemes);
234 }
235
236 if let Some(other_security) = &mut other.security {
237 let security = self.security.get_or_insert(Vec::new());
238 other_security.retain(|requirement| !security.contains(requirement));
239 security.append(other_security);
240 }
241
242 if let Some(other_tags) = &mut other.tags {
243 let tags = self.tags.get_or_insert(Vec::new());
244 other_tags.retain(|tag| !tags.contains(tag));
245 tags.append(other_tags);
246 }
247 }
248
249 pub fn nest<P: Into<String>, O: Into<OpenApi>>(self, path: P, other: O) -> Self {
291 self.nest_with_path_composer(path, other, |base, path| format!("{base}{path}"))
292 }
293
294 pub fn nest_with_path_composer<
301 P: Into<String>,
302 O: Into<OpenApi>,
303 F: Fn(&str, &str) -> String,
304 >(
305 mut self,
306 path: P,
307 other: O,
308 composer: F,
309 ) -> Self {
310 let path: String = path.into();
311 let mut other_api: OpenApi = other.into();
312
313 let nested_paths = other_api.paths.paths.into_iter().map(|(item_path, item)| {
314 let path = composer(&path, &item_path);
315 (path, item)
316 });
317
318 self.paths.paths.extend(nested_paths);
319
320 other_api.paths.paths = IndexMap::new();
322 self.merge_from(other_api)
323 }
324}
325
326#[derive(Serialize, Clone, PartialEq, Eq, Default)]
330#[cfg_attr(feature = "debug", derive(Debug))]
331pub enum OpenApiVersion {
332 #[serde(rename = "3.1.0")]
334 #[default]
335 Version31,
336}
337
338impl<'de> serde::Deserialize<'de> for OpenApiVersion {
339 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
340 where
341 D: Deserializer<'de>,
342 {
343 struct VersionVisitor;
344
345 impl<'v> Visitor<'v> for VersionVisitor {
346 type Value = OpenApiVersion;
347
348 fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
349 formatter.write_str("a version string in 3.1.x format")
350 }
351
352 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
353 where
354 E: Error,
355 {
356 self.visit_string(v.to_string())
357 }
358
359 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
360 where
361 E: Error,
362 {
363 let version = v
364 .split('.')
365 .flat_map(|digit| digit.parse::<i8>())
366 .collect::<Vec<_>>();
367
368 if version.len() == 3 && version.first() == Some(&3) && version.get(1) == Some(&1) {
369 Ok(OpenApiVersion::Version31)
370 } else {
371 let expected: &dyn Expected = &"3.1.0";
372 Err(Error::invalid_value(
373 serde::de::Unexpected::Str(&v),
374 expected,
375 ))
376 }
377 }
378 }
379
380 deserializer.deserialize_string(VersionVisitor)
381 }
382}
383
384#[derive(PartialEq, Eq, Clone, Default)]
388#[cfg_attr(feature = "debug", derive(Debug))]
389#[allow(missing_docs)]
390pub enum Deprecated {
391 True,
392 #[default]
393 False,
394}
395
396impl serde::Serialize for Deprecated {
397 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
398 where
399 S: Serializer,
400 {
401 serializer.serialize_bool(matches!(self, Self::True))
402 }
403}
404
405impl<'de> serde::Deserialize<'de> for Deprecated {
406 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
407 where
408 D: serde::Deserializer<'de>,
409 {
410 struct BoolVisitor;
411 impl<'de> Visitor<'de> for BoolVisitor {
412 type Value = Deprecated;
413
414 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
415 formatter.write_str("a bool true or false")
416 }
417
418 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
419 where
420 E: serde::de::Error,
421 {
422 match v {
423 true => Ok(Deprecated::True),
424 false => Ok(Deprecated::False),
425 }
426 }
427 }
428 deserializer.deserialize_bool(BoolVisitor)
429 }
430}
431
432#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
437#[cfg_attr(feature = "debug", derive(Debug))]
438#[serde(untagged)]
439pub enum RefOr<T> {
440 Ref(Ref),
443 T(T),
446}
447
448use crate::extensions::Extensions;
449
450#[cfg(test)]
451#[cfg_attr(coverage_nightly, coverage(off))]
452mod tests {
453 use insta::assert_json_snapshot;
454
455 use super::response::Response;
456 use super::*;
457 use crate::path::Operation;
458
459 #[test]
460 fn serialize_deserialize_openapi_version_success() -> Result<(), serde_json::Error> {
461 assert_eq!(serde_json::to_value(&OpenApiVersion::Version31)?, "3.1.0");
462 Ok(())
463 }
464
465 #[test]
466 fn serialize_openapi_json_minimal_success() {
467 let openapi = OpenApi::new(
468 Info::builder()
469 .title("My api")
470 .version("1.0.0")
471 .description("My api description")
472 .license(License::builder().name("MIT").url("http://mit.licence")),
473 Paths::new(),
474 );
475
476 assert_json_snapshot!(openapi);
477 }
478
479 #[test]
480 fn serialize_openapi_json_with_paths_success() {
481 let openapi = OpenApi::new(
482 Info::new("My big api", "1.1.0"),
483 Paths::builder()
484 .path(
485 "/api/v1/users",
486 PathItem::new(
487 HttpMethod::Get,
488 Operation::builder().response("200", Response::new("Get users list")),
489 ),
490 )
491 .path(
492 "/api/v1/users",
493 PathItem::new(
494 HttpMethod::Post,
495 Operation::builder().response("200", Response::new("Post new user")),
496 ),
497 )
498 .path(
499 "/api/v1/users/{id}",
500 PathItem::new(
501 HttpMethod::Get,
502 Operation::builder().response("200", Response::new("Get user by id")),
503 ),
504 ),
505 );
506
507 assert_json_snapshot!(openapi);
508 }
509
510 #[test]
511 fn merge_2_openapi_documents() {
512 let mut api_1 = OpenApi::new(
513 Info::new("Api", "v1"),
514 Paths::builder()
515 .path(
516 "/api/v1/user",
517 PathItem::new(
518 HttpMethod::Get,
519 Operation::builder().response("200", Response::new("Get user success")),
520 ),
521 )
522 .build(),
523 );
524
525 let api_2 = OpenApi::builder()
526 .info(Info::new("Api", "v2"))
527 .paths(
528 Paths::builder()
529 .path(
530 "/api/v1/user",
531 PathItem::new(
532 HttpMethod::Get,
533 Operation::builder()
534 .response("200", Response::new("This will not get added")),
535 ),
536 )
537 .path(
538 "/ap/v2/user",
539 PathItem::new(
540 HttpMethod::Get,
541 Operation::builder()
542 .response("200", Response::new("Get user success 2")),
543 ),
544 )
545 .path(
546 "/api/v2/user",
547 PathItem::new(
548 HttpMethod::Post,
549 Operation::builder().response("200", Response::new("Get user success")),
550 ),
551 )
552 .build(),
553 )
554 .components(
555 Components::builder().schema(
556 "User2",
557 Object::builder()
558 .schema_type(Type::Object)
559 .property("name", Object::builder().schema_type(Type::String)),
560 ),
561 )
562 .build();
563
564 api_1.merge(api_2);
565
566 assert_json_snapshot!(api_1, {
567 ".paths" => insta::sorted_redaction()
568 });
569 }
570
571 #[test]
572 fn merge_same_path_diff_methods() {
573 let mut api_1 = OpenApi::new(
574 Info::new("Api", "v1"),
575 Paths::builder()
576 .path(
577 "/api/v1/user",
578 PathItem::new(
579 HttpMethod::Get,
580 Operation::builder().response("200", Response::new("Get user success 1")),
581 ),
582 )
583 .extensions(Extensions::from_iter([("x-v1-api", true)]))
584 .build(),
585 );
586
587 let api_2 = OpenApi::builder()
588 .info(Info::new("Api", "v2"))
589 .paths(
590 Paths::builder()
591 .path(
592 "/api/v1/user",
593 PathItem::new(
594 HttpMethod::Get,
595 Operation::builder()
596 .response("200", Response::new("This will not get added")),
597 ),
598 )
599 .path(
600 "/api/v1/user",
601 PathItem::new(
602 HttpMethod::Post,
603 Operation::builder()
604 .response("200", Response::new("Post user success 1")),
605 ),
606 )
607 .path(
608 "/api/v2/user",
609 PathItem::new(
610 HttpMethod::Get,
611 Operation::builder()
612 .response("200", Response::new("Get user success 2")),
613 ),
614 )
615 .path(
616 "/api/v2/user",
617 PathItem::new(
618 HttpMethod::Post,
619 Operation::builder()
620 .response("200", Response::new("Post user success 2")),
621 ),
622 )
623 .extensions(Extensions::from_iter([("x-random", "Value")])),
624 )
625 .components(
626 Components::builder().schema(
627 "User2",
628 Object::builder()
629 .schema_type(Type::Object)
630 .property("name", Object::builder().schema_type(Type::String)),
631 ),
632 )
633 .build();
634
635 api_1.merge(api_2);
636
637 assert_json_snapshot!(api_1, {
638 ".paths" => insta::sorted_redaction()
639 });
640 }
641
642 #[test]
643 fn test_nest_open_apis() {
644 let api = OpenApi::builder()
645 .paths(Paths::builder().path(
646 "/api/v1/status",
647 PathItem::new(
648 HttpMethod::Get,
649 Operation::builder().description("Get status"),
650 ),
651 ))
652 .build();
653
654 let user_api = OpenApi::builder()
655 .paths(
656 Paths::builder()
657 .path(
658 "/",
659 PathItem::new(
660 HttpMethod::Get,
661 Operation::builder().description("Get user details").build(),
662 ),
663 )
664 .path(
665 "/foo",
666 PathItem::new(HttpMethod::Post, Operation::builder().build()),
667 ),
668 )
669 .build();
670
671 let nest_merged = api.nest("/api/v1/user", user_api);
672 let value = serde_json::to_value(nest_merged).expect("should serialize as json");
673 let paths = value
674 .pointer("/paths")
675 .expect("paths should exits in openapi");
676
677 assert_json_snapshot!(paths);
678 }
679
680 #[test]
681 fn openapi_custom_extension() {
682 let mut api = OpenApi::builder().build();
683 let extensions = api.extensions.get_or_insert(Default::default());
684 extensions.insert(
685 String::from("x-tagGroup"),
686 String::from("anything that serializes to Json").into(),
687 );
688
689 assert_json_snapshot!(api);
690 }
691}