1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! Response Object
use crate::common::helpers::{Context, PushError, ValidateWithContext, validate_required_string};
use crate::common::reference::RefOr;
use crate::v3_0::header::Header;
use crate::v3_0::link::Link;
use crate::v3_0::media_type::MediaType;
use crate::v3_0::spec::Spec;
use crate::validation::Options;
use serde::de::{Error, MapAccess, Visitor};
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
use std::fmt;
/// A container for the expected responses of an operation.
/// The container maps a HTTP response code to the expected response.
///
/// The documentation is not necessarily expected to cover all possible HTTP response codes
/// because they may not be known in advance.
/// However, documentation is expected to cover a successful operation response and any known errors.
///
/// The `default` MAY be used as a default response object for all HTTP codes that are
/// not covered individually by the specification.
///
/// The `Responses Object` MUST contain at least one response code,
/// and it SHOULD be the response for a successful operation call.
///
/// Specification example:
/// ```yaml
/// '200':
/// description: a pet to be returned
/// content:
/// application/json:
/// schema:
/// $ref: '#/components/schemas/Pet'
/// default:
/// description: Unexpected error
/// content:
/// application/json:
/// schema:
/// $ref: '#/components/schemas/ErrorModel'
/// ```
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Responses {
/// The documentation of responses other than the ones declared for specific HTTP response codes.
/// Use this field to cover undeclared responses.
/// A Reference Object can link to a response that the OpenAPI Object’s components/responses
/// section defines.
pub default: Option<RefOr<Response>>,
/// Any HTTP status code can be used as the property name,
/// but only one property per code,
/// to describe the expected response for that HTTP status code.
/// A Reference Object can link to a response that is defined in the OpenAPI Object’s
/// components/responses section.
/// This field MUST be enclosed in quotation marks (for example, “200”) for compatibility
/// between JSON and YAML.
/// To define a range of response codes, this field MAY contain the uppercase wildcard character `X`.
/// For example, `2XX` represents all response codes between `[200-299]`.
/// Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`.
/// If a response is defined using an explicit code,
/// the explicit code definition takes precedence over the range definition for that code.
pub responses: Option<BTreeMap<String, RefOr<Response>>>,
/// Allows extensions to the Swagger Schema.
/// The field name MUST begin with `x-`, for example, `x-internal-id`.
/// The value can be null, a primitive, an array or an object.
pub extensions: Option<BTreeMap<String, serde_json::Value>>,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)]
pub struct Response {
/// **Required** A short description of the response.
/// [CommonMark](https://spec.commonmark.org) syntax MAY be used for rich text representation.
#[serde(skip_serializing_if = "String::is_empty")]
pub description: String,
/// Maps a header name to its definition.
/// [RFC7230](https://www.rfc-editor.org/rfc/rfc7230) states header names are case insensitive.
/// If a response header is defined with the name `"Content-Type"`, it SHALL be ignored.
#[serde(skip_serializing_if = "Option::is_none")]
pub headers: Option<BTreeMap<String, RefOr<Header>>>,
/// A map containing descriptions of potential response payloads.
/// The key is a media type or media type range and the value describes it.
/// For responses that match multiple keys, only the most specific key is applicable.
/// e.g. `text/plain` overrides `text/*`
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<BTreeMap<String, MediaType>>,
/// Maps a header name to its definition.
/// [RFC7230](https://www.rfc-editor.org/rfc/rfc7230) states header names are case insensitive.
/// If a response header is defined with the name `"Content-Type"`, it SHALL be ignored.
#[serde(skip_serializing_if = "Option::is_none")]
pub links: Option<BTreeMap<String, RefOr<Link>>>,
/// A map of operations links that can be followed from the response.
/// The key of the map is a short name for the link,
/// following the naming constraints of the names for Component Objects.
#[serde(flatten)]
#[serde(with = "crate::common::extensions")]
#[serde(skip_serializing_if = "Option::is_none")]
pub extensions: Option<BTreeMap<String, serde_json::Value>>,
}
impl Serialize for Responses {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(None)?;
if let Some(ref default) = self.default {
map.serialize_entry("default", default)?;
}
if let Some(ref responses) = self.responses {
for (k, v) in responses {
map.serialize_entry(&k, &v)?;
}
}
if let Some(ref ext) = self.extensions {
for (k, v) in ext {
if k.starts_with("x-") {
map.serialize_entry(&k, &v)?;
}
}
}
map.end()
}
}
impl<'de> Deserialize<'de> for Responses {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
const FIELDS: &[&str] = &["default", "x-...", "1xx", "2xx", "3xx", "4xx", "5xx"];
struct ResponsesVisitor;
impl<'de> Visitor<'de> for ResponsesVisitor {
type Value = Responses;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("struct Responses")
}
fn visit_map<V>(self, mut map: V) -> Result<Responses, V::Error>
where
V: MapAccess<'de>,
{
let mut res = Responses::default();
let mut responses: BTreeMap<String, RefOr<Response>> = BTreeMap::new();
let mut extensions: BTreeMap<String, serde_json::Value> = BTreeMap::new();
while let Some(key) = map.next_key::<String>()? {
if key == "default" {
if res.default.is_some() {
return Err(Error::duplicate_field("default"));
}
res.default = Some(map.next_value()?);
} else if key.starts_with("x-") {
if extensions.contains_key(key.as_str()) {
return Err(Error::custom(format_args!("duplicate field `{key}`")));
}
extensions.insert(key, map.next_value()?);
} else {
match key.parse::<u16>() {
Ok(100..=599) => {
if responses.contains_key(key.as_str()) {
return Err(Error::custom(format_args!(
"duplicate field `{key}`"
)));
}
responses.insert(key, map.next_value()?);
}
_ => return Err(Error::unknown_field(key.as_str(), FIELDS)),
}
}
}
if !responses.is_empty() {
res.responses = Some(responses);
}
if !extensions.is_empty() {
res.extensions = Some(extensions);
}
Ok(res)
}
}
deserializer.deserialize_struct("Responses", FIELDS, ResponsesVisitor)
}
}
impl ValidateWithContext<Spec> for Response {
fn validate_with_context(&self, ctx: &mut Context<Spec>, path: String) {
if !ctx.is_option(Options::IgnoreEmptyResponseDescription) {
validate_required_string(&self.description, ctx, format!("{path}.description"));
}
if let Some(headers) = &self.headers {
for (name, header) in headers {
header.validate_with_context(ctx, format!("{path}.headers[{name}]"));
}
}
if let Some(media_types) = &self.content {
for (name, media_type) in media_types {
media_type.validate_with_context(ctx, format!("{path}.mediaTypes[{name}]"));
}
}
if let Some(links) = &self.links {
for (name, link) in links {
link.validate_with_context(ctx, format!("{path}.links[{name}]"));
}
}
}
}
impl ValidateWithContext<Spec> for Responses {
fn validate_with_context(&self, ctx: &mut Context<Spec>, path: String) {
if let Some(response) = &self.default {
response.validate_with_context(ctx, format!("{path}.default"));
}
if let Some(responses) = &self.responses {
for (name, response) in responses {
match name.parse::<u16>() {
Ok(100..=599) => {}
_ => {
ctx.error(
path.clone(),
format_args!(
"name must be an integer within [100..599] range, found `{name}`"
),
);
}
}
response.validate_with_context(ctx, format!("{path}.{name}"));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::v3_0::parameter::InHeaderStyle;
use crate::v3_0::schema::{ObjectSchema, Schema, SingleSchema};
#[test]
fn test_response_deserialize() {
assert_eq!(
serde_json::from_value::<Response>(serde_json::json!({
"description": "A simple response",
"headers": {
"Authorization": {
"description": "A short description of the header.",
"style": "simple",
"required": true,
},
},
"content": {
"application/json": {
"schema": {
"type": "object",
"title": "foo"
}
}
},
"links": {
"next": {
"operationRef": "getNextPage",
"description": "Get the next page of results"
}
},
"x-extra": "extension",
}))
.unwrap(),
Response {
description: "A simple response".to_owned(),
headers: Some({
let mut map = BTreeMap::new();
map.insert(
"Authorization".to_owned(),
RefOr::new_item(Header {
description: Some("A short description of the header.".to_owned()),
required: Some(true),
style: Some(InHeaderStyle::Simple),
..Default::default()
}),
);
map
}),
content: Some({
let mut map = BTreeMap::new();
map.insert(
"application/json".to_owned(),
MediaType {
schema: Some(RefOr::new_item(Schema::Single(Box::new(
SingleSchema::Object(ObjectSchema {
title: Some("foo".to_owned()),
..Default::default()
}),
)))),
..Default::default()
},
);
map
}),
links: Some({
let mut map = BTreeMap::new();
map.insert(
"next".to_owned(),
RefOr::new_item(Link {
operation_ref: Some("getNextPage".to_owned()),
description: Some("Get the next page of results".to_owned()),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
},
"response deserialization",
);
}
#[test]
fn test_response_serialization() {
assert_eq!(
serde_json::to_value(Response {
description: "A simple response".to_owned(),
headers: Some({
let mut map = BTreeMap::new();
map.insert(
"Authorization".to_owned(),
RefOr::new_item(Header {
description: Some("A short description of the header.".to_owned()),
required: Some(true),
style: Some(InHeaderStyle::Simple),
..Default::default()
}),
);
map
}),
content: Some({
let mut map = BTreeMap::new();
map.insert(
"application/json".to_owned(),
MediaType {
schema: Some(RefOr::new_item(Schema::Single(Box::new(
SingleSchema::Object(ObjectSchema {
title: Some("foo".to_owned()),
..Default::default()
}),
)))),
..Default::default()
},
);
map
}),
links: Some({
let mut map = BTreeMap::new();
map.insert(
"next".to_owned(),
RefOr::new_item(Link {
operation_ref: Some("getNextPage".to_owned()),
description: Some("Get the next page of results".to_owned()),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
})
.unwrap(),
serde_json::json!({
"description": "A simple response",
"headers": {
"Authorization": {
"description": "A short description of the header.",
"style": "simple",
"required": true,
},
},
"content": {
"application/json": {
"schema": {
"type": "object",
"title": "foo"
}
}
},
"links": {
"next": {
"operationRef": "getNextPage",
"description": "Get the next page of results"
}
},
"x-extra": "extension",
}),
"response serialization",
);
}
#[test]
fn test_responses_deserialize() {
assert_eq!(
serde_json::from_value::<Responses>(serde_json::json!({
"default": {
"description": "A simple response",
"headers": {
"Authorization": {
"description": "A short description of the header.",
"style": "simple",
"required": true,
},
},
"content": {
"application/json": {
"schema": {
"type": "object",
"title": "foo"
}
}
},
"links": {
"next": {
"operationRef": "getNextPage",
"description": "Get the next page of results"
}
},
"x-extra": "extension",
},
"200": {
"description": "200 OK"
},
"x-extra": "extension",
}))
.unwrap(),
Responses {
default: Some(RefOr::new_item(Response {
description: "A simple response".to_owned(),
headers: Some({
let mut map = BTreeMap::new();
map.insert(
"Authorization".to_owned(),
RefOr::new_item(Header {
description: Some("A short description of the header.".to_owned()),
required: Some(true),
style: Some(InHeaderStyle::Simple),
..Default::default()
}),
);
map
}),
content: Some({
let mut map = BTreeMap::new();
map.insert(
"application/json".to_owned(),
MediaType {
schema: Some(RefOr::new_item(Schema::Single(Box::new(
SingleSchema::Object(ObjectSchema {
title: Some("foo".to_owned()),
..Default::default()
}),
)))),
..Default::default()
},
);
map
}),
links: Some({
let mut map = BTreeMap::new();
map.insert(
"next".to_owned(),
RefOr::new_item(Link {
operation_ref: Some("getNextPage".to_owned()),
description: Some("Get the next page of results".to_owned()),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
})),
responses: Some({
let mut map = BTreeMap::new();
map.insert(
"200".to_owned(),
RefOr::new_item(Response {
description: "200 OK".to_owned(),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
},
"responses deserialization",
);
}
#[test]
fn test_responses_serialization() {
assert_eq!(
serde_json::to_value(Responses {
default: Some(RefOr::new_item(Response {
description: "A simple response".to_owned(),
headers: Some({
let mut map = BTreeMap::new();
map.insert(
"Authorization".to_owned(),
RefOr::new_item(Header {
description: Some("A short description of the header.".to_owned()),
required: Some(true),
style: Some(InHeaderStyle::Simple),
..Default::default()
}),
);
map
}),
content: Some({
let mut map = BTreeMap::new();
map.insert(
"application/json".to_owned(),
MediaType {
schema: Some(RefOr::new_item(Schema::Single(Box::new(
SingleSchema::Object(ObjectSchema {
title: Some("foo".to_owned()),
..Default::default()
}),
)))),
..Default::default()
},
);
map
}),
links: Some({
let mut map = BTreeMap::new();
map.insert(
"next".to_owned(),
RefOr::new_item(Link {
operation_ref: Some("getNextPage".to_owned()),
description: Some("Get the next page of results".to_owned()),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
})),
responses: Some({
let mut map = BTreeMap::new();
map.insert(
"200".to_owned(),
RefOr::new_item(Response {
description: "200 OK".to_owned(),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
})
.unwrap(),
serde_json::json!({
"default": {
"description": "A simple response",
"headers": {
"Authorization": {
"description": "A short description of the header.",
"style": "simple",
"required": true,
},
},
"content": {
"application/json": {
"schema": {
"type": "object",
"title": "foo"
}
}
},
"links": {
"next": {
"operationRef": "getNextPage",
"description": "Get the next page of results"
}
},
"x-extra": "extension",
},
"200": {
"description": "200 OK"
},
"x-extra": "extension",
}),
"response serialization",
);
}
#[test]
fn test_response_validate() {
let spec = Spec::default();
let mut ctx = Context::new(&spec, Options::new());
Response {
description: "A simple response".to_owned(),
headers: Some({
let mut map = BTreeMap::new();
map.insert(
"Authorization".to_owned(),
RefOr::new_item(Header {
description: Some("A short description of the header.".to_owned()),
required: Some(true),
style: Some(InHeaderStyle::Simple),
..Default::default()
}),
);
map
}),
content: Some({
let mut map = BTreeMap::new();
map.insert(
"application/json".to_owned(),
MediaType {
schema: Some(RefOr::new_item(Schema::Single(Box::new(
SingleSchema::Object(ObjectSchema {
title: Some("foo".to_owned()),
..Default::default()
}),
)))),
..Default::default()
},
);
map
}),
links: Some({
let mut map = BTreeMap::new();
map.insert(
"next".to_owned(),
RefOr::new_item(Link {
operation_ref: Some("getNextPage".to_owned()),
description: Some("Get the next page of results".to_owned()),
..Default::default()
}),
);
map
}),
extensions: Some({
let mut map = BTreeMap::new();
map.insert("x-extra".to_owned(), serde_json::json!("extension"));
map
}),
}
.validate_with_context(&mut ctx, "response".to_owned());
assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);
let mut ctx = Context::new(&spec, Options::new());
Response {
description: "A simple response".to_owned(),
..Default::default()
}
.validate_with_context(&mut ctx, "response".to_owned());
assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);
let mut ctx = Context::new(&spec, Options::new());
Response::default().validate_with_context(&mut ctx, "response".to_owned());
assert!(
ctx.errors
.contains(&"response.description: must not be empty".to_string()),
"expected error: {:?}",
ctx.errors
);
let mut ctx = Context::new(
&spec,
Options::only(&Options::IgnoreEmptyResponseDescription),
);
Response::default().validate_with_context(&mut ctx, "response".to_owned());
assert!(ctx.errors.is_empty(), "no errors: {:?}", ctx.errors);
}
}