Skip to main content

oas31/
lib.rs

1//! Rust implementation of OpenAPI Spec v3.1.x
2//!
3//! A lof the code was taken from [`utoipa`](https://crates.io/crates/utoipa).
4//!
5//! The main difference is the full JSON Schema 2020-12 Definitions.
6#![cfg_attr(feature = "docs", doc = "## Feature flags")]
7#![cfg_attr(feature = "docs", doc = document_features::document_features!())]
8//! ## Alternatives
9//!
10//! - [`openapiv3`](https://crates.io/crates/openapiv3): Implements the openapi v3.0.x spec, does not implement full json schema draft 2020-12 spec.
11//! - [`utoipa`](https://crates.io/crates/utoipa): A fully fletched openapi-type-generator implementing some of the v3.1.x spec.
12//! - [`schemars`](https://crates.io/crates/schemars): A fully fletched jsonschema-type-generator implementing some of the json schema draft 2020-12 spec.
13//!
14//! ## License
15//!
16//! This project is licensed under the MIT or Apache-2.0 license.
17//! You can choose between one of them if you use this work.
18//!
19//! `SPDX-License-Identifier: MIT OR Apache-2.0`
20#![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/// Root object of the OpenAPI document.
63///
64/// You can use [`OpenApi::new`] function to construct a new [`OpenApi`] instance and then
65/// use the fields with mutable access to modify them. This is quite tedious if you are not simply
66/// just changing one thing thus you can also use the [`OpenApi::builder`] to use builder to
67/// construct a new [`OpenApi`] object.
68///
69/// See more details at <https://spec.openapis.org/oas/latest.html#openapi-object>.
70#[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    /// OpenAPI document version.
79    #[builder(default)]
80    pub openapi: OpenApiVersion,
81
82    /// Provides metadata about the API.
83    ///
84    /// See more details at <https://spec.openapis.org/oas/latest.html#info-object>.
85    #[builder(default)]
86    pub info: Info,
87
88    /// Optional list of servers that provides the connectivity information to target servers.
89    ///
90    /// This is implicitly one server with `url` set to `/`.
91    ///
92    /// See more details at <https://spec.openapis.org/oas/latest.html#server-object>.
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub servers: Option<Vec<Server>>,
95
96    /// Available paths and operations for the API.
97    ///
98    /// See more details at <https://spec.openapis.org/oas/latest.html#paths-object>.
99    #[builder(default)]
100    pub paths: Paths,
101
102    /// Holds various reusable schemas for the OpenAPI document.
103    ///
104    /// Few of these elements are security schemas and object schemas.
105    ///
106    /// See more details at <https://spec.openapis.org/oas/latest.html#components-object>.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub components: Option<Components>,
109
110    /// Declaration of global security mechanisms that can be used across the API. The individual operations
111    /// can override the declarations. You can use `SecurityRequirement::default()` if you wish to make security
112    /// optional by adding it to the list of securities.
113    ///
114    /// See more details at <https://spec.openapis.org/oas/latest.html#security-requirement-object>.
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub security: Option<Vec<SecurityRequirement>>,
117
118    /// Optional list of tags can be used to add additional documentation to matching tags of operations.
119    ///
120    /// See more details at <https://spec.openapis.org/oas/latest.html#tag-object>.
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub tags: Option<Vec<Tag>>,
123
124    /// Optional global additional documentation reference.
125    ///
126    /// See more details at <https://spec.openapis.org/oas/latest.html#external-documentation-object>.
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub external_docs: Option<ExternalDocs>,
129
130    /// Schema keyword can be used to override default _`$schema`_ dialect which is by default
131    /// "<https://spec.openapis.org/oas/3.1/dialect/base>".
132    ///
133    /// All the references and individual files could use their own schema dialect.
134    #[serde(rename = "$schema", default, skip_serializing_if = "String::is_empty")]
135    #[builder(default)]
136    pub schema: String,
137
138    /// Optional extensions "x-something".
139    #[serde(skip_serializing_if = "Option::is_none", flatten)]
140    pub extensions: Option<Extensions>,
141}
142
143impl OpenApi {
144    /// Construct a new [`OpenApi`] object.
145    ///
146    /// Function accepts two arguments one which is [`Info`] metadata of the API; two which is [`Paths`]
147    /// containing operations for the API.
148    ///
149    /// # Examples
150    ///
151    /// ```rust
152    /// # use oas31::{Info, Paths, OpenApi};
153    /// #
154    /// let openapi = OpenApi::new(Info::new("pet api", "0.1.0"), Paths::new());
155    /// ```
156    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    /// Converts this [`OpenApi`] to JSON String. This method essentially calls [`serde_json::to_string`] method.
165    pub fn to_json(&self) -> Result<String, serde_json::Error> {
166        serde_json::to_string(self)
167    }
168
169    /// Converts this [`OpenApi`] to pretty JSON String. This method essentially calls [`serde_json::to_string_pretty`] method.
170    pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
171        serde_json::to_string_pretty(self)
172    }
173
174    /// Converts this [`OpenApi`] to YAML String. This method essentially calls [`serde_norway::to_string`] method.
175    #[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    /// Merge `other` [`OpenApi`] moving `self` and returning combined [`OpenApi`].
182    ///
183    /// In functionality wise this is exactly same as calling [`OpenApi::merge`] but but provides
184    /// leaner API for chaining method calls.
185    pub fn merge_from(mut self, other: OpenApi) -> OpenApi {
186        self.merge(other);
187        self
188    }
189
190    /// Merge `other` [`OpenApi`] consuming it and resuming it's content.
191    ///
192    /// Merge function will take all `self` nonexistent _`servers`, `paths`, `schemas`, `responses`,
193    /// `security_schemes`, `security_requirements` and `tags`_ from _`other`_ [`OpenApi`].
194    ///
195    /// This function performs a shallow comparison for `paths`, `schemas`, `responses` and
196    /// `security schemes` which means that only _`name`_ and _`path`_ is used for comparison. When
197    /// match occurs the whole item will be ignored from merged results. Only items not
198    /// found will be appended to `self`.
199    ///
200    /// For _`servers`_, _`tags`_ and _`security_requirements`_ the whole item will be used for
201    /// comparison. Items not found from `self` will be appended to `self`.
202    ///
203    /// **Note!** `info`, `openapi`, `external_docs` and `schema` will not be merged.
204    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    /// Nest `other` [`OpenApi`] to this [`OpenApi`].
250    ///
251    /// Nesting performs custom [`OpenApi::merge`] where `other` [`OpenApi`] paths are prepended with given
252    /// `path` and then appended to _`paths`_ of this [`OpenApi`] instance. Rest of the  `other`
253    /// [`OpenApi`] instance is merged to this [`OpenApi`] with [`OpenApi::merge_from`] method.
254    ///
255    /// **If multiple** APIs are being nested with same `path` only the **last** one will be retained.
256    ///
257    /// Method accepts two arguments, first is the path to prepend .e.g. _`/user`_. Second argument
258    /// is the [`OpenApi`] to prepend paths for.
259    ///
260    /// # Examples
261    ///
262    /// _**Merge `user_api` to `api` nesting `user_api` paths under `/api/v1/user`**_
263    /// ```rust
264    ///  # use oas31::{OpenApi, OpenApiBuilder};
265    ///  # use oas31::path::{Paths, PathItem,
266    ///  # HttpMethod, Operation};
267    ///  let api = OpenApi::builder()
268    ///      .paths(
269    ///          Paths::builder().path(
270    ///              "/api/v1/status",
271    ///              PathItem::new(
272    ///                  HttpMethod::Get,
273    ///                  Operation::builder()
274    ///                      .description("Get status")
275    ///                      .build(),
276    ///              ),
277    ///          ),
278    ///      )
279    ///      .build();
280    ///  let user_api = OpenApi::builder()
281    ///     .paths(
282    ///         Paths::builder().path(
283    ///             "/",
284    ///             PathItem::new(HttpMethod::Post, Operation::builder().build()),
285    ///         )
286    ///     )
287    ///     .build();
288    ///  let nested = api.nest("/api/v1/user", user_api);
289    /// ```
290    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    /// Nest `other` [`OpenApi`] with custom path composer.
295    ///
296    /// In most cases you should use [`OpenApi::nest`] instead.
297    /// Only use this method if you need custom path composition for a specific use case.
298    ///
299    /// `composer` is a function that takes two strings, the base path and the path to nest, and returns the composed path for the API Specification.
300    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        // paths are already merged, thus we can ignore them
321        other_api.paths.paths = IndexMap::new();
322        self.merge_from(other_api)
323    }
324}
325
326/// Represents available [OpenAPI versions][version].
327///
328/// [version]: <https://spec.openapis.org/oas/latest.html#versions>
329#[derive(Serialize, Clone, PartialEq, Eq, Default)]
330#[cfg_attr(feature = "debug", derive(Debug))]
331pub enum OpenApiVersion {
332    /// Will serialize to `3.1.0` the latest released OpenAPI version.
333    #[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/// Value used to indicate whether reusable schema, parameter or operation is deprecated.
385///
386/// The value will serialize to boolean.
387#[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/// A [`Ref`] or some other type `T`.
433///
434/// Typically used in combination with [`Components`] and is an union type between [`Ref`] and any
435/// other given type such as [`Schema`] or [`Response`].
436#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
437#[cfg_attr(feature = "debug", derive(Debug))]
438#[serde(untagged)]
439pub enum RefOr<T> {
440    /// Represents [`Ref`] reference to another OpenAPI object instance. e.g.
441    /// `$ref: #/components/schemas/Hello`
442    Ref(Ref),
443    /// Represents any value that can be added to the [`struct@Components`] e.g. [`enum@Schema`]
444    /// or [`struct@Response`].
445    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}