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
pub use self::{
components::Components,
content::Content,
example::Example,
external_docs::ExternalDocs,
header::Header,
info::{Contact, Info, License},
operation::{Operation, Operations},
parameter::{Parameter, ParameterIn, ParameterStyle, Parameters},
path::{PathItem, PathItemType, Paths},
request_body::RequestBody,
response::{Response, Responses},
schema::{
Array, Discriminator, KnownFormat, Object, Ref, Schema, SchemaFormat, SchemaType, ToArray,
},
security::{SecurityRequirement, SecurityScheme},
server::{Server, ServerVariable, ServerVariables, Servers},
tag::Tag,
xml::Xml,
};
use serde::{de::Visitor, Deserialize, Serialize, Serializer};
use std::collections::BTreeSet;
pub mod components;
pub mod content;
pub mod encoding;
pub mod example;
pub mod external_docs;
pub mod header;
pub mod info;
pub mod operation;
pub mod parameter;
pub mod path;
pub mod request_body;
pub mod response;
pub mod schema;
pub mod security;
pub mod server;
pub mod tag;
pub mod xml;
/// Root object of the OpenAPI document.
///
/// You can use [`OpenApi::new`] function to construct a new [`OpenApi`] instance and then
/// use the fields with mutable access to modify them. This is quite tedious if you are not simply
/// just changing one thing thus you can also use the [`OpenApiBuilder::new`] to use builder to
/// construct a new [`OpenApi`] object.
///
/// See more details at <https://spec.openapis.org/oas/latest.html#openapi-object>.
#[non_exhaustive]
#[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[serde(rename_all = "camelCase")]
pub struct OpenApi {
/// OpenAPI document version.
pub openapi: OpenApiVersion,
/// Provides metadata about the API.
/// See more details at <https://spec.openapis.org/oas/latest.html#info-object>.
pub info: Info,
/// List of servers that provides the connectivity information to target servers.
/// This is implicitly one server with `url` set to `/`.
/// See more details at <https://spec.openapis.org/oas/latest.html#server-object>.
#[serde(skip_serializing_if = "BTreeSet::is_empty")]
pub servers: BTreeSet<Server>,
/// Available paths and operations for the API.
/// See more details at <https://spec.openapis.org/oas/latest.html#paths-object>.
pub paths: Paths, // PathItem 需要 Operation
/// Holds various reusable schemas for the OpenAPI document.
/// Few of these elements are security schemas and object schemas.
/// See more details at <https://spec.openapis.org/oas/latest.html#components-object>.
#[serde(skip_serializing_if = "Components::is_empty")]
pub components: Components,
/// Declaration of global security mechanisms that can be used across the API. The individual operations
/// can override the declarations. You can use `SecurityRequirement::default()` if you wish to make security
/// optional by adding it to the list of securities.
/// See more details at <https://spec.openapis.org/oas/latest.html#security-requirement-object>.
#[serde(skip_serializing_if = "BTreeSet::is_empty")]
pub security: BTreeSet<SecurityRequirement>,
/// List of tags can be used to add additional documentation to matching tags of operations.
/// See more details at <https://spec.openapis.org/oas/latest.html#tag-object>.
#[serde(skip_serializing_if = "BTreeSet::is_empty")]
pub tags: BTreeSet<Tag>,
/// Global additional documentation reference.
/// See more details at <https://spec.openapis.org/oas/latest.html#external-documentation-object>.
#[serde(skip_serializing_if = "Option::is_none")]
pub external_docs: Option<ExternalDocs>,
}
impl OpenApi {
/// Construct a new [`OpenApi`] object.
///
/// Function accepts two arguments one which is [`Info`] metadata of the API; two which is [`Paths`]
/// containing operations for the API.
///
/// # Examples
///
/// ```rust
/// # use hypers_openapi::{Info, Paths, OpenApi};
/// #
/// let openapi = OpenApi::new("pet api", "0.1.0");
/// ```
pub fn new(title: impl Into<String>, version: impl Into<String>) -> Self {
Self {
info: Info::new(title, version),
..Default::default()
}
}
pub fn with_info(info: Info) -> Self {
Self {
info,
..Default::default()
}
}
/// Converts this [`OpenApi`] to JSON String. This method essentially calls [`serde_json::to_string`] method.
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
/// Converts this [`OpenApi`] to pretty JSON String. This method essentially calls [`serde_json::to_string_pretty`] method.
pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
/// Converts this [`OpenApi`] to YAML String. This method essentially calls [`serde_yaml::to_string`] method.
#[cfg(feature = "yaml")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "yaml")))]
pub fn to_yaml(&self) -> Result<String, serde_yaml::Error> {
serde_yaml::to_string(self)
}
/// Merge `other` [`OpenApi`] consuming it and resuming it's content.
///
/// Merge function will take all `self` nonexistent _`servers`, `paths`, `schemas`, `responses`,
/// `security_schemes`, `security_requirements` and `tags`_ from _`other`_ [`OpenApi`].
///
/// This function performs a shallow comparison for `paths`, `schemas`, `responses` and
/// `security schemes` which means that only _`name`_ and _`path`_ is used for comparison. When
/// match occurs the whole item will be ignored from merged results. Only items not
/// found will be appended to `self`.
///
/// For _`servers`_, _`tags`_ and _`security_requirements`_ the whole item will be used for
/// comparison. Items not found from `self` will be appended to `self`.
///
/// **Note!** `info`, `openapi` and `external_docs` will not be merged.
pub fn merge(mut self, mut other: OpenApi) -> Self {
self.servers.append(&mut other.servers);
self.paths.append(&mut other.paths);
self.components.append(&mut other.components);
self.security.append(&mut other.security);
self.tags.append(&mut other.tags);
self
}
/// Add [`Info`] metadata of the API.
pub fn info<I: Into<Info>>(mut self, info: I) -> Self {
self.info = info.into();
self
}
/// Add iterator of [`Server`]s to configure target servers.
pub fn servers<S: IntoIterator<Item = Server>>(mut self, servers: S) -> Self {
self.servers = servers.into_iter().collect();
self
}
/// Add [`Server`] to configure operations and endpoints of the API and returns `Self`.
pub fn add_server<S>(mut self, server: S) -> Self
where
S: Into<Server>,
{
self.servers.insert(server.into());
self
}
/// Set paths to configure operations and endpoints of the API.
pub fn paths<P: Into<Paths>>(mut self, paths: P) -> Self {
self.paths = paths.into();
self
}
#[inline]
pub fn metadata(mut self, mut meta: (String, PathItem, Components)) -> Self {
self.paths.insert(meta.0, meta.1);
self.components.append(&mut meta.2);
self
}
/// Add [`PathItem`] to configure operations and endpoints of the API and returns `Self`.
pub fn add_path<P, I>(mut self, path: P, item: I) -> Self
where
P: Into<String>,
I: Into<PathItem>,
{
self.paths.insert(path.into(), item.into());
self
}
/// Add [`Components`] to configure reusable schemas.
pub fn components(mut self, components: impl Into<Components>) -> Self {
self.components = components.into();
self
}
/// Add iterator of [`SecurityRequirement`]s that are globally available for all operations.
pub fn security<S: IntoIterator<Item = SecurityRequirement>>(mut self, security: S) -> Self {
self.security = security.into_iter().collect();
self
}
/// Add [`SecurityScheme`] to [`Components`] and returns `Self`.
///
/// Accepts two arguments where first is the name of the [`SecurityScheme`]. This is later when
/// referenced by [`SecurityRequirement`][requirement]s. Second parameter is the [`SecurityScheme`].
///
/// [requirement]: crate::SecurityRequirement
pub fn add_security_scheme<N: Into<String>, S: Into<SecurityScheme>>(
mut self,
name: N,
security_scheme: S,
) -> Self {
self.components
.security_schemes
.insert(name.into(), security_scheme.into());
self
}
/// Add iterator of [`SecurityScheme`]s to [`Components`].
///
/// Accepts two arguments where first is the name of the [`SecurityScheme`]. This is later when
/// referenced by [`SecurityRequirement`][requirement]s. Second parameter is the [`SecurityScheme`].
///
/// [requirement]: crate::SecurityRequirement
pub fn extend_security_schemes<
I: IntoIterator<Item = (N, S)>,
N: Into<String>,
S: Into<SecurityScheme>,
>(
mut self,
schemas: I,
) -> Self {
self.components.security_schemes.extend(
schemas
.into_iter()
.map(|(name, item)| (name.into(), item.into())),
);
self
}
/// Add [`Schema`] to [`Components`] and returns `Self`.
///
/// Accepts two arguments where first is name of the schema and second is the schema itself.
pub fn add_schema<S: Into<String>, I: Into<RefOr<Schema>>>(
mut self,
name: S,
schema: I,
) -> Self {
self.components.schemas.insert(name.into(), schema.into());
self
}
/// Add [`Schema`]s from iterator.
///
/// # Examples
/// ```
/// # use hypers_openapi::{OpenApi, Object, SchemaType, Schema};
/// OpenApi::new("api", "0.0.1").extend_schemas([(
/// "Pet",
/// Schema::from(
/// Object::new()
/// .property(
/// "name",
/// Object::new().schema_type(SchemaType::String),
/// )
/// .required("name")
/// ),
/// )]);
/// ```
pub fn extend_schemas<I, C, S>(mut self, schemas: I) -> Self
where
I: IntoIterator<Item = (S, C)>,
C: Into<RefOr<Schema>>,
S: Into<String>,
{
self.components.schemas.extend(
schemas
.into_iter()
.map(|(name, schema)| (name.into(), schema.into())),
);
self
}
/// Add a new response and returns `self`.
pub fn response<S: Into<String>, R: Into<RefOr<Response>>>(
mut self,
name: S,
response: R,
) -> Self {
self.components
.responses
.insert(name.into(), response.into());
self
}
/// Extends responses with the contents of an iterator.
pub fn extend_responses<
I: IntoIterator<Item = (S, R)>,
S: Into<String>,
R: Into<RefOr<Response>>,
>(
mut self,
responses: I,
) -> Self {
self.components.responses.extend(
responses
.into_iter()
.map(|(name, response)| (name.into(), response.into())),
);
self
}
/// Add iterator of [`Tag`]s to add additional documentation for **operations** tags.
pub fn tags<I, T>(mut self, tags: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Tag>,
{
self.tags = tags.into_iter().map(Into::into).collect();
self
}
/// Add [`ExternalDocs`] for referring additional documentation.
pub fn external_docs(mut self, external_docs: ExternalDocs) -> Self {
self.external_docs = Some(external_docs);
self
}
}
/// Represents available [OpenAPI versions][version].
///
/// [version]: <https://spec.openapis.org/oas/latest.html#versions>
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub enum OpenApiVersion {
/// Will serialize to `3.1.0` the latest from 3.0 serde.
#[serde(rename = "3.1.0")]
Version3,
}
impl Default for OpenApiVersion {
fn default() -> Self {
Self::Version3
}
}
/// Value used to indicate whether reusable schema, parameter or operation is deprecated.
///
/// The value will serialize to boolean.
#[derive(PartialEq, Eq, Clone)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub enum Deprecated {
True,
False,
}
impl From<bool> for Deprecated {
fn from(b: bool) -> Self {
if b {
Self::True
} else {
Self::False
}
}
}
impl Serialize for Deprecated {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bool(matches!(self, Self::True))
}
}
impl<'de> Deserialize<'de> for Deprecated {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct BoolVisitor;
impl<'de> Visitor<'de> for BoolVisitor {
type Value = Deprecated;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a bool true or false")
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match v {
true => Ok(Deprecated::True),
false => Ok(Deprecated::False),
}
}
}
deserializer.deserialize_bool(BoolVisitor)
}
}
impl Default for Deprecated {
fn default() -> Self {
Deprecated::False
}
}
/// Value used to indicate whether parameter or property is required.
///
/// The value will serialize to boolean.
#[derive(PartialEq, Eq, Clone, Default)]
#[cfg_attr(feature = "debug", derive(Debug))]
pub enum Required {
/// Is required.
True,
/// Is not required.
False,
/// This value is not set, it will treat as `False` when serialize to boolean.
#[default]
Unset,
}
impl From<bool> for Required {
fn from(value: bool) -> Self {
if value {
Self::True
} else {
Self::False
}
}
}
impl Serialize for Required {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_bool(matches!(self, Self::True))
}
}
impl<'de> Deserialize<'de> for Required {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct BoolVisitor;
impl<'de> Visitor<'de> for BoolVisitor {
type Value = Required;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a bool true or false")
}
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
match v {
true => Ok(Required::True),
false => Ok(Required::False),
}
}
}
deserializer.deserialize_bool(BoolVisitor)
}
}
/// A [`Ref`] or some other type `T`.
///
/// Typically used in combination with [`Components`] and is an union type between [`Ref`] and any
/// other given type such as [`Schema`] or [`Response`].
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
#[serde(untagged)]
pub enum RefOr<T> {
/// A [`Ref`] to a reusable component.
Ref(schema::Ref),
/// Some other type `T`.
T(T),
}