openapi-to-rust 0.3.0

Generate strongly-typed Rust structs, HTTP clients, and SSE streaming clients from OpenAPI 3.1 specifications
Documentation
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct OpenApiSpec {
    pub openapi: String,
    pub info: Info,
    pub paths: Option<BTreeMap<String, PathItem>>,
    pub components: Option<Components>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Info {
    pub title: String,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Components {
    pub schemas: Option<BTreeMap<String, Schema>>,
    pub parameters: Option<BTreeMap<String, Parameter>>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Schema {
    /// Schema reference
    Reference {
        #[serde(rename = "$ref")]
        reference: String,
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// Recursive reference (OpenAPI 3.1)
    RecursiveRef {
        #[serde(rename = "$recursiveRef")]
        recursive_ref: String,
        #[serde(flatten)]
        extra: BTreeMap<String, Value>,
    },
    /// OneOf union
    OneOf {
        #[serde(rename = "oneOf")]
        one_of: Vec<Schema>,
        discriminator: Option<Discriminator>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// AnyOf union (must come before Typed to handle type + anyOf patterns)
    AnyOf {
        #[serde(rename = "type")]
        schema_type: Option<SchemaType>,
        #[serde(rename = "anyOf")]
        any_of: Vec<Schema>,
        discriminator: Option<Discriminator>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// Schema with explicit type
    Typed {
        #[serde(rename = "type")]
        schema_type: SchemaType,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// AllOf composition
    AllOf {
        #[serde(rename = "allOf")]
        all_of: Vec<Schema>,
        #[serde(flatten)]
        details: SchemaDetails,
    },
    /// Schema without explicit type (inferred from other fields)
    Untyped {
        #[serde(flatten)]
        details: SchemaDetails,
    },
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SchemaType {
    String,
    Integer,
    Number,
    Boolean,
    Array,
    Object,
    #[serde(rename = "null")]
    Null,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SchemaDetails {
    pub description: Option<String>,
    pub nullable: Option<bool>,

    // OpenAPI 3.1 recursive support
    #[serde(rename = "$recursiveAnchor")]
    pub recursive_anchor: Option<bool>,

    // String-specific
    #[serde(rename = "enum")]
    pub enum_values: Option<Vec<Value>>,
    pub format: Option<String>,
    pub default: Option<Value>,
    #[serde(rename = "const")]
    pub const_value: Option<Value>,

    // Object-specific
    pub properties: Option<BTreeMap<String, Schema>>,
    pub required: Option<Vec<String>>,
    #[serde(rename = "additionalProperties")]
    pub additional_properties: Option<AdditionalProperties>,

    // Array-specific
    pub items: Option<Box<Schema>>,

    // Number-specific
    pub minimum: Option<f64>,
    pub maximum: Option<f64>,

    // Validation
    #[serde(rename = "minLength")]
    pub min_length: Option<u64>,
    #[serde(rename = "maxLength")]
    pub max_length: Option<u64>,
    pub pattern: Option<String>,

    // Extensions and unknown fields
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(untagged)]
pub enum AdditionalProperties {
    Boolean(bool),
    Schema(Box<Schema>),
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Discriminator {
    #[serde(rename = "propertyName")]
    pub property_name: String,
    pub mapping: Option<BTreeMap<String, String>>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl Schema {
    /// Get the schema type if explicitly set
    pub fn schema_type(&self) -> Option<&SchemaType> {
        match self {
            Schema::Typed { schema_type, .. } => Some(schema_type),
            _ => None,
        }
    }

    /// Get schema details
    pub fn details(&self) -> &SchemaDetails {
        match self {
            Schema::Typed { details, .. } => details,
            Schema::Reference { .. } => {
                static EMPTY_DETAILS: Lazy<SchemaDetails> = Lazy::new(|| SchemaDetails {
                    description: None,
                    nullable: None,
                    recursive_anchor: None,
                    enum_values: None,
                    format: None,
                    default: None,
                    const_value: None,
                    properties: None,
                    required: None,
                    additional_properties: None,
                    items: None,
                    minimum: None,
                    maximum: None,
                    min_length: None,
                    max_length: None,
                    pattern: None,
                    extra: BTreeMap::new(),
                });
                &EMPTY_DETAILS
            }
            Schema::RecursiveRef { .. } => {
                static EMPTY_DETAILS_RECURSIVE: Lazy<SchemaDetails> = Lazy::new(|| SchemaDetails {
                    description: None,
                    nullable: None,
                    recursive_anchor: None,
                    enum_values: None,
                    format: None,
                    default: None,
                    const_value: None,
                    properties: None,
                    required: None,
                    additional_properties: None,
                    items: None,
                    minimum: None,
                    maximum: None,
                    min_length: None,
                    max_length: None,
                    pattern: None,
                    extra: BTreeMap::new(),
                });
                &EMPTY_DETAILS_RECURSIVE
            }
            Schema::OneOf { details, .. } => details,
            Schema::AnyOf { details, .. } => details,
            Schema::AllOf { details, .. } => details,
            Schema::Untyped { details } => details,
        }
    }

    /// Get mutable schema details
    pub fn details_mut(&mut self) -> &mut SchemaDetails {
        match self {
            Schema::Typed { details, .. } => details,
            Schema::Reference { .. } => {
                // Cannot mutate reference details
                panic!("Cannot get mutable details for reference schema")
            }
            Schema::RecursiveRef { .. } => {
                // Cannot mutate recursive reference details
                panic!("Cannot get mutable details for recursive reference schema")
            }
            Schema::OneOf { details, .. } => details,
            Schema::AnyOf { details, .. } => details,
            Schema::AllOf { details, .. } => details,
            Schema::Untyped { details } => details,
        }
    }

    /// Check if this is any kind of reference (regular or recursive)
    pub fn is_reference(&self) -> bool {
        matches!(self, Schema::Reference { .. } | Schema::RecursiveRef { .. })
    }

    /// Get reference string if this is a reference
    pub fn reference(&self) -> Option<&str> {
        match self {
            Schema::Reference { reference, .. } => Some(reference),
            _ => None,
        }
    }

    /// Get recursive reference string if this is a recursive reference
    pub fn recursive_reference(&self) -> Option<&str> {
        match self {
            Schema::RecursiveRef { recursive_ref, .. } => Some(recursive_ref),
            _ => None,
        }
    }

    /// Check if this is a discriminated union
    pub fn is_discriminated_union(&self) -> bool {
        match self {
            Schema::OneOf { discriminator, .. } => discriminator.is_some(),
            Schema::AnyOf { discriminator, .. } => discriminator.is_some(),
            _ => false,
        }
    }

    /// Get discriminator if this is a discriminated union
    pub fn discriminator(&self) -> Option<&Discriminator> {
        match self {
            Schema::OneOf { discriminator, .. } => discriminator.as_ref(),
            Schema::AnyOf { discriminator, .. } => discriminator.as_ref(),
            _ => None,
        }
    }

    /// Get union variants
    pub fn union_variants(&self) -> Option<&[Schema]> {
        match self {
            Schema::OneOf { one_of, .. } => Some(one_of),
            Schema::AnyOf { any_of, .. } => Some(any_of),
            _ => None,
        }
    }

    /// Check if this appears to be a nullable pattern (anyOf or oneOf with null)
    pub fn is_nullable_pattern(&self) -> bool {
        let variants = match self {
            Schema::AnyOf { any_of, .. } => any_of,
            Schema::OneOf { one_of, .. } => one_of,
            _ => return false,
        };
        variants.len() == 2
            && variants
                .iter()
                .any(|s| matches!(s.schema_type(), Some(SchemaType::Null)))
    }

    /// Get the non-null variant from a nullable pattern
    pub fn non_null_variant(&self) -> Option<&Schema> {
        if !self.is_nullable_pattern() {
            return None;
        }
        let variants = match self {
            Schema::AnyOf { any_of, .. } => any_of,
            Schema::OneOf { one_of, .. } => one_of,
            _ => return None,
        };
        variants
            .iter()
            .find(|s| !matches!(s.schema_type(), Some(SchemaType::Null)))
    }

    /// Infer schema type from structure if not explicitly set
    pub fn inferred_type(&self) -> Option<SchemaType> {
        match self {
            Schema::Typed { schema_type, .. } => Some(schema_type.clone()),
            Schema::Untyped { details } => {
                // Infer from structure
                if details.properties.is_some() {
                    Some(SchemaType::Object)
                } else if details.items.is_some() {
                    Some(SchemaType::Array)
                } else if details.enum_values.is_some() {
                    Some(SchemaType::String) // Assume string enum
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

impl SchemaDetails {
    /// Check if this schema is nullable
    pub fn is_nullable(&self) -> bool {
        self.nullable.unwrap_or(false)
    }

    /// Check if this is a string enum
    ///
    /// A standalone string `const` (no `enum` array) is treated as a
    /// degenerate single-value enum so the generator emits a tightly-typed
    /// single-variant enum instead of a bare `String`. See issue #10.
    pub fn is_string_enum(&self) -> bool {
        self.enum_values.is_some() || self.const_string_value().is_some()
    }

    /// Get enum values as strings if this is a string enum.
    ///
    /// Falls back to `[const_value]` when `enum` is absent but `const` is a
    /// string, so a property like `{ "type": "string", "const": "X" }`
    /// produces a single-variant enum.
    pub fn string_enum_values(&self) -> Option<Vec<String>> {
        if let Some(values) = self.enum_values.as_ref() {
            return Some(
                values
                    .iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect(),
            );
        }
        self.const_string_value().map(|s| vec![s])
    }

    fn const_string_value(&self) -> Option<String> {
        self.const_value
            .as_ref()
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    /// Check if a field is required
    pub fn is_field_required(&self, field_name: &str) -> bool {
        self.required
            .as_ref()
            .map(|req| req.contains(&field_name.to_string()))
            .unwrap_or(false)
    }
}

/// OpenAPI Path Item Object  
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PathItem {
    #[serde(rename = "get")]
    pub get: Option<Operation>,
    #[serde(rename = "put")]
    pub put: Option<Operation>,
    #[serde(rename = "post")]
    pub post: Option<Operation>,
    #[serde(rename = "delete")]
    pub delete: Option<Operation>,
    #[serde(rename = "options")]
    pub options: Option<Operation>,
    #[serde(rename = "head")]
    pub head: Option<Operation>,
    #[serde(rename = "patch")]
    pub patch: Option<Operation>,
    #[serde(rename = "trace")]
    pub trace: Option<Operation>,
    pub parameters: Option<Vec<Parameter>>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl PathItem {
    /// Get all operations in this path item
    pub fn operations(&self) -> Vec<(&str, &Operation)> {
        let mut ops = Vec::new();
        if let Some(ref op) = self.get {
            ops.push(("get", op));
        }
        if let Some(ref op) = self.put {
            ops.push(("put", op));
        }
        if let Some(ref op) = self.post {
            ops.push(("post", op));
        }
        if let Some(ref op) = self.delete {
            ops.push(("delete", op));
        }
        if let Some(ref op) = self.options {
            ops.push(("options", op));
        }
        if let Some(ref op) = self.head {
            ops.push(("head", op));
        }
        if let Some(ref op) = self.patch {
            ops.push(("patch", op));
        }
        if let Some(ref op) = self.trace {
            ops.push(("trace", op));
        }
        ops
    }
}

/// OpenAPI Operation Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Operation {
    #[serde(rename = "operationId")]
    pub operation_id: Option<String>,
    pub summary: Option<String>,
    pub description: Option<String>,
    pub parameters: Option<Vec<Parameter>>,
    #[serde(rename = "requestBody")]
    pub request_body: Option<RequestBody>,
    pub responses: Option<BTreeMap<String, Response>>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// OpenAPI Parameter Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Parameter {
    pub name: Option<String>,
    #[serde(rename = "in")]
    pub location: Option<String>,
    pub required: Option<bool>,
    pub schema: Option<Schema>,
    pub description: Option<String>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// OpenAPI Request Body Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RequestBody {
    pub content: Option<BTreeMap<String, MediaType>>,
    pub description: Option<String>,
    pub required: Option<bool>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// Returns true for media types whose payload is JSON.
///
/// Matches `application/json` exactly, plus any RFC 6839 structured-syntax
/// suffix variant of the form `application/<subtype>+json`
/// (e.g. `application/vnd.api+json`, `application/hal+json`,
/// `application/problem+json`). Trailing parameters such as
/// `; charset=utf-8` are tolerated.
pub fn is_json_media_type(ct: &str) -> bool {
    let essence = ct
        .split(';')
        .next()
        .unwrap_or(ct)
        .trim()
        .to_ascii_lowercase();
    if essence == "application/json" {
        return true;
    }
    if let Some(subtype) = essence.strip_prefix("application/") {
        return subtype.ends_with("+json");
    }
    false
}

/// Returns true for `application/x-www-form-urlencoded` (with optional
/// parameters).
pub fn is_form_urlencoded_media_type(ct: &str) -> bool {
    let essence = ct
        .split(';')
        .next()
        .unwrap_or(ct)
        .trim()
        .to_ascii_lowercase();
    essence == "application/x-www-form-urlencoded"
}

fn find_json_content(content: &BTreeMap<String, MediaType>) -> Option<(&str, &MediaType)> {
    if let Some(mt) = content.get("application/json") {
        return Some(("application/json", mt));
    }
    content
        .iter()
        .find(|(ct, _)| is_json_media_type(ct))
        .map(|(ct, mt)| (ct.as_str(), mt))
}

impl RequestBody {
    /// Get schema for any JSON content type
    ///
    /// Prefers the canonical `application/json` entry, then falls back to
    /// any `application/*+json` variant (RFC 6839) such as
    /// `application/vnd.api+json` or `application/hal+json`.
    pub fn json_schema(&self) -> Option<&Schema> {
        self.content
            .as_ref()
            .and_then(find_json_content)
            .and_then(|(_, media_type)| media_type.schema.as_ref())
    }

    /// Get the best content type and its schema, preferring JSON over others
    pub fn best_content(&self) -> Option<(&str, Option<&Schema>)> {
        let content = self.content.as_ref()?;

        if let Some((ct, media_type)) = find_json_content(content) {
            return Some((ct, media_type.schema.as_ref()));
        }

        const PRIORITY: &[&str] = &[
            "application/x-www-form-urlencoded",
            "multipart/form-data",
            "application/octet-stream",
            "text/plain",
        ];
        for ct in PRIORITY {
            if let Some(media_type) = content.get(*ct) {
                return Some((*ct, media_type.schema.as_ref()));
            }
        }
        None
    }
}

/// OpenAPI Response Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Response {
    pub description: Option<String>,
    pub content: Option<BTreeMap<String, MediaType>>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl Response {
    /// Get schema for any JSON content type
    ///
    /// Prefers the canonical `application/json` entry, then falls back to
    /// any `application/*+json` variant (RFC 6839) such as
    /// `application/vnd.api+json`, `application/hal+json`, or
    /// `application/problem+json`.
    pub fn json_schema(&self) -> Option<&Schema> {
        self.content
            .as_ref()
            .and_then(find_json_content)
            .and_then(|(_, media_type)| media_type.schema.as_ref())
    }
}

/// OpenAPI Media Type Object
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MediaType {
    pub schema: Option<Schema>,
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_parse_simple_object_schema() {
        let schema_json = json!({
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "User name"
                },
                "age": {
                    "type": "integer"
                }
            },
            "required": ["name"]
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        match schema {
            Schema::Typed {
                schema_type: SchemaType::Object,
                details,
            } => {
                assert!(details.properties.is_some());
                assert_eq!(details.required, Some(vec!["name".to_string()]));
                assert!(details.is_field_required("name"));
                assert!(!details.is_field_required("age"));
            }
            _ => panic!("Expected object schema"),
        }
    }

    #[test]
    fn test_parse_string_enum() {
        let schema_json = json!({
            "type": "string",
            "enum": ["active", "inactive", "pending"],
            "description": "User status"
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        match schema {
            Schema::Typed {
                schema_type: SchemaType::String,
                details,
            } => {
                assert!(details.is_string_enum());
                let values = details.string_enum_values().unwrap();
                assert_eq!(values, vec!["active", "inactive", "pending"]);
            }
            _ => panic!("Expected string enum schema"),
        }
    }

    #[test]
    fn test_parse_reference_schema() {
        let schema_json = json!({
            "$ref": "#/components/schemas/User"
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        assert!(schema.is_reference());
        assert_eq!(schema.reference(), Some("#/components/schemas/User"));
    }

    #[test]
    fn test_parse_discriminated_union() {
        let schema_json = json!({
            "oneOf": [
                {"$ref": "#/components/schemas/Dog"},
                {"$ref": "#/components/schemas/Cat"}
            ],
            "discriminator": {
                "propertyName": "petType"
            }
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        assert!(schema.is_discriminated_union());
        let discriminator = schema.discriminator().unwrap();
        assert_eq!(discriminator.property_name, "petType");
    }

    #[test]
    fn test_parse_nullable_pattern() {
        let schema_json = json!({
            "anyOf": [
                {"$ref": "#/components/schemas/User"},
                {"type": "null"}
            ]
        });

        let schema: Schema = serde_json::from_value(schema_json).unwrap();

        assert!(schema.is_nullable_pattern());
        let non_null = schema.non_null_variant().unwrap();
        assert!(non_null.is_reference());
    }

    #[test]
    fn is_json_media_type_accepts_canonical_and_structured_suffix() {
        // Canonical
        assert!(is_json_media_type("application/json"));
        // Parameters tolerated (RFC 7231 ยง3.1.1.1)
        assert!(is_json_media_type("application/json; charset=utf-8"));
        assert!(is_json_media_type("APPLICATION/JSON"));
        // RFC 6839 +json structured-syntax suffix
        assert!(is_json_media_type("application/vnd.api+json"));
        assert!(is_json_media_type("application/hal+json"));
        assert!(is_json_media_type("application/problem+json"));
        assert!(is_json_media_type("application/ld+json"));
        assert!(is_json_media_type(
            "application/vnd.api+json; charset=utf-8"
        ));
        // Negatives
        assert!(!is_json_media_type("application/xml"));
        assert!(!is_json_media_type("application/x-www-form-urlencoded"));
        assert!(!is_json_media_type("text/plain"));
        assert!(!is_json_media_type("application/jsonbutnotreally"));
        // +json suffix only applies to application/* per RFC 6839
        assert!(!is_json_media_type("text/something+json"));
    }

    #[test]
    fn request_body_json_schema_finds_vnd_api_plus_json() {
        // Mirrors Latitude.sh: request body declared under
        // application/vnd.api+json without a sibling application/json.
        let body_json = json!({
            "required": true,
            "content": {
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/create_api_key"}
                }
            }
        });

        let body: RequestBody = serde_json::from_value(body_json).unwrap();
        let schema = body.json_schema().expect("expected +json schema match");
        assert!(schema.is_reference());
    }

    #[test]
    fn request_body_best_content_prefers_canonical_json_over_plus_json() {
        // When both are present (e.g. Latitude.sh's POST /auth/api_keys),
        // best_content should still pick application/json for backwards
        // compatibility with the existing snapshot suite.
        let body_json = json!({
            "required": true,
            "content": {
                "application/json": {
                    "schema": {"$ref": "#/components/schemas/A"}
                },
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/B"}
                }
            }
        });

        let body: RequestBody = serde_json::from_value(body_json).unwrap();
        let (ct, _) = body.best_content().expect("expected best_content");
        assert_eq!(ct, "application/json");
    }

    #[test]
    fn request_body_best_content_falls_back_to_plus_json() {
        // When only the +json variant is declared, best_content returns
        // it instead of skipping straight to form-urlencoded.
        let body_json = json!({
            "required": true,
            "content": {
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/B"}
                }
            }
        });

        let body: RequestBody = serde_json::from_value(body_json).unwrap();
        let (ct, _) = body.best_content().expect("expected best_content");
        assert_eq!(ct, "application/vnd.api+json");
    }

    #[test]
    fn response_json_schema_finds_vnd_api_plus_json() {
        // Mirrors every Latitude.sh response: schema lives under
        // application/vnd.api+json only.
        let resp_json = json!({
            "description": "OK",
            "content": {
                "application/vnd.api+json": {
                    "schema": {"$ref": "#/components/schemas/api_keys"}
                }
            }
        });

        let resp: Response = serde_json::from_value(resp_json).unwrap();
        let schema = resp.json_schema().expect("expected +json schema match");
        assert!(schema.is_reference());
    }
}