Skip to main content

fastapi_openapi/
schema.rs

1//! JSON Schema types for OpenAPI 3.1.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// JSON Schema representation.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8#[serde(untagged)]
9pub enum Schema {
10    /// Boolean schema (true = any, false = none).
11    Boolean(bool),
12    /// Reference to another schema.
13    Ref(RefSchema),
14    /// Enum schema (string values).
15    Enum(EnumSchema),
16    /// OneOf schema (union type).
17    OneOf(OneOfSchema),
18    /// AnyOf schema (a union whose branches may overlap).
19    AnyOf(AnyOfSchema),
20    /// Array schema.
21    #[serde(serialize_with = "serialize_array_schema")]
22    Array(ArraySchema),
23    /// Primitive type schema.
24    #[serde(serialize_with = "serialize_primitive_schema")]
25    Primitive(PrimitiveSchema),
26    /// Object schema. Keep the all-optional object variant last when decoding.
27    #[serde(serialize_with = "serialize_object_schema")]
28    Object(ObjectSchema),
29}
30
31#[derive(Serialize)]
32struct TypedSchema<'a, T> {
33    #[serde(rename = "type")]
34    kind: &'static str,
35    #[serde(flatten)]
36    schema: &'a T,
37}
38
39fn serialize_primitive_schema<S: serde::Serializer>(
40    schema: &PrimitiveSchema,
41    serializer: S,
42) -> Result<S::Ok, S::Error> {
43    if schema.nullable {
44        let mut non_null = schema.clone();
45        non_null.nullable = false;
46        Schema::any_of(vec![Schema::Primitive(non_null), <()>::schema()]).serialize(serializer)
47    } else {
48        schema.serialize(serializer)
49    }
50}
51
52fn serialize_object_schema<S: serde::Serializer>(
53    schema: &ObjectSchema,
54    serializer: S,
55) -> Result<S::Ok, S::Error> {
56    TypedSchema {
57        kind: "object",
58        schema,
59    }
60    .serialize(serializer)
61}
62
63fn serialize_array_schema<S: serde::Serializer>(
64    schema: &ArraySchema,
65    serializer: S,
66) -> Result<S::Ok, S::Error> {
67    TypedSchema {
68        kind: "array",
69        schema,
70    }
71    .serialize(serializer)
72}
73
74impl Schema {
75    /// Create a string schema.
76    pub fn string() -> Self {
77        Schema::Primitive(PrimitiveSchema::string())
78    }
79
80    /// Create an integer schema with optional format.
81    pub fn integer(format: Option<&str>) -> Self {
82        Schema::Primitive(PrimitiveSchema::integer(format))
83    }
84
85    /// Create a number schema with optional format.
86    pub fn number(format: Option<&str>) -> Self {
87        Schema::Primitive(PrimitiveSchema::number(format))
88    }
89
90    /// Create a boolean schema.
91    pub fn boolean() -> Self {
92        Schema::Primitive(PrimitiveSchema::boolean())
93    }
94
95    /// Create a reference schema.
96    pub fn reference(name: &str) -> Self {
97        Schema::Ref(RefSchema {
98            reference: format!("#/components/schemas/{name}"),
99        })
100    }
101
102    /// Create an array schema.
103    pub fn array(items: Schema) -> Self {
104        Schema::Array(ArraySchema {
105            items: Box::new(items),
106            min_items: None,
107            max_items: None,
108        })
109    }
110
111    /// Create an object schema with the given properties.
112    pub fn object(properties: HashMap<String, Schema>, required: Vec<String>) -> Self {
113        Schema::Object(ObjectSchema {
114            title: None,
115            description: None,
116            properties,
117            required,
118            additional_properties: None,
119        })
120    }
121
122    /// Permit null. Non-primitive schemas use a union with the null schema.
123    #[must_use]
124    pub fn nullable(mut self) -> Self {
125        if let Schema::Primitive(ref mut p) = self {
126            p.nullable = true;
127            self
128        } else {
129            Self::any_of(vec![self, <()>::schema()])
130        }
131    }
132
133    /// Set title on this schema (if object).
134    #[must_use]
135    pub fn with_title(mut self, title: impl Into<String>) -> Self {
136        if let Schema::Object(ref mut o) = self {
137            o.title = Some(title.into());
138        }
139        self
140    }
141
142    /// Set description on this schema (if object).
143    #[must_use]
144    pub fn with_description(mut self, description: impl Into<String>) -> Self {
145        if let Schema::Object(ref mut o) = self {
146            o.description = Some(description.into());
147        }
148        self
149    }
150
151    /// Create a string enum schema with allowed values.
152    pub fn string_enum(values: Vec<String>) -> Self {
153        Schema::Enum(EnumSchema {
154            schema_type: SchemaType::String,
155            enum_values: values,
156        })
157    }
158
159    /// Create a oneOf schema (union type).
160    pub fn one_of(schemas: Vec<Schema>) -> Self {
161        Schema::OneOf(OneOfSchema { one_of: schemas })
162    }
163
164    /// Create an inclusive union, permitting values accepted by any branch.
165    pub fn any_of(schemas: Vec<Schema>) -> Self {
166        Schema::AnyOf(AnyOfSchema { any_of: schemas })
167    }
168}
169
170/// Schema reference.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct RefSchema {
173    /// Reference path (e.g., "#/components/schemas/Item").
174    #[serde(rename = "$ref")]
175    pub reference: String,
176}
177
178/// Object schema.
179#[derive(Debug, Clone, Default, Serialize, Deserialize)]
180pub struct ObjectSchema {
181    /// Schema title.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub title: Option<String>,
184    /// Schema description.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub description: Option<String>,
187    /// Object properties.
188    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
189    pub properties: HashMap<String, Schema>,
190    /// Required property names.
191    #[serde(default, skip_serializing_if = "Vec::is_empty")]
192    pub required: Vec<String>,
193    /// Additional properties schema.
194    #[serde(
195        rename = "additionalProperties",
196        default,
197        skip_serializing_if = "Option::is_none"
198    )]
199    pub additional_properties: Option<Box<Schema>>,
200}
201
202/// Array schema.
203#[derive(Debug, Clone, Serialize, Deserialize)]
204pub struct ArraySchema {
205    /// Item schema.
206    pub items: Box<Schema>,
207    /// Minimum items.
208    #[serde(rename = "minItems", default, skip_serializing_if = "Option::is_none")]
209    pub min_items: Option<usize>,
210    /// Maximum items.
211    #[serde(rename = "maxItems", default, skip_serializing_if = "Option::is_none")]
212    pub max_items: Option<usize>,
213}
214
215/// Enum schema with allowed values.
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct EnumSchema {
218    /// JSON Schema type (typically string for enums).
219    #[serde(rename = "type")]
220    pub schema_type: SchemaType,
221    /// Allowed enum values.
222    #[serde(rename = "enum")]
223    pub enum_values: Vec<String>,
224}
225
226/// OneOf schema (union type).
227#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct OneOfSchema {
229    /// List of possible schemas.
230    #[serde(rename = "oneOf")]
231    pub one_of: Vec<Schema>,
232}
233
234/// Inclusive union, used for nullable types whose inner schema may allow null.
235#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct AnyOfSchema {
237    /// Alternatives; a value must match at least one.
238    #[serde(rename = "anyOf")]
239    pub any_of: Vec<Schema>,
240}
241
242/// Primitive type schema.
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct PrimitiveSchema {
245    /// JSON Schema type.
246    #[serde(rename = "type")]
247    pub schema_type: SchemaType,
248    /// Format hint.
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    pub format: Option<String>,
251    /// Nullable flag (OpenAPI 3.1).
252    #[serde(default, skip_serializing_if = "is_false")]
253    pub nullable: bool,
254}
255
256impl PrimitiveSchema {
257    /// Create a string schema.
258    pub fn string() -> Self {
259        Self {
260            schema_type: SchemaType::String,
261            format: None,
262            nullable: false,
263        }
264    }
265
266    /// Create an integer schema with optional format.
267    pub fn integer(format: Option<&str>) -> Self {
268        Self {
269            schema_type: SchemaType::Integer,
270            format: format.map(String::from),
271            nullable: false,
272        }
273    }
274
275    /// Create a number schema with optional format.
276    pub fn number(format: Option<&str>) -> Self {
277        Self {
278            schema_type: SchemaType::Number,
279            format: format.map(String::from),
280            nullable: false,
281        }
282    }
283
284    /// Create a boolean schema.
285    pub fn boolean() -> Self {
286        Self {
287            schema_type: SchemaType::Boolean,
288            format: None,
289            nullable: false,
290        }
291    }
292}
293
294#[allow(clippy::trivially_copy_pass_by_ref)]
295fn is_false(b: &bool) -> bool {
296    !*b
297}
298
299/// JSON Schema primitive types.
300#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
301#[serde(rename_all = "lowercase")]
302pub enum SchemaType {
303    /// String type.
304    String,
305    /// Number type (float).
306    Number,
307    /// Integer type.
308    Integer,
309    /// Boolean type.
310    Boolean,
311    /// Null type.
312    Null,
313}
314
315/// Trait for types that can generate JSON Schema.
316pub trait JsonSchema {
317    /// Generate the JSON Schema for this type.
318    fn schema() -> Schema;
319
320    /// Get the schema name for use in `#/components/schemas/`.
321    #[must_use]
322    fn schema_name() -> Option<&'static str> {
323        None
324    }
325}
326
327// Implement for primitive types
328impl JsonSchema for String {
329    fn schema() -> Schema {
330        Schema::Primitive(PrimitiveSchema {
331            schema_type: SchemaType::String,
332            format: None,
333            nullable: false,
334        })
335    }
336}
337
338impl JsonSchema for i64 {
339    fn schema() -> Schema {
340        Schema::Primitive(PrimitiveSchema {
341            schema_type: SchemaType::Integer,
342            format: Some("int64".to_string()),
343            nullable: false,
344        })
345    }
346}
347
348impl JsonSchema for i32 {
349    fn schema() -> Schema {
350        Schema::Primitive(PrimitiveSchema {
351            schema_type: SchemaType::Integer,
352            format: Some("int32".to_string()),
353            nullable: false,
354        })
355    }
356}
357
358impl JsonSchema for f64 {
359    fn schema() -> Schema {
360        Schema::Primitive(PrimitiveSchema {
361            schema_type: SchemaType::Number,
362            format: Some("double".to_string()),
363            nullable: false,
364        })
365    }
366}
367
368impl JsonSchema for bool {
369    fn schema() -> Schema {
370        Schema::Primitive(PrimitiveSchema {
371            schema_type: SchemaType::Boolean,
372            format: None,
373            nullable: false,
374        })
375    }
376}
377
378macro_rules! integer_schema {
379    ($ty:ty, $format:expr) => {
380        impl JsonSchema for $ty {
381            fn schema() -> Schema {
382                Schema::integer($format)
383            }
384        }
385    };
386}
387
388integer_schema!(i8, Some("int8"));
389integer_schema!(i16, Some("int16"));
390integer_schema!(u8, Some("uint8"));
391integer_schema!(u16, Some("uint16"));
392integer_schema!(u32, Some("uint32"));
393integer_schema!(u64, Some("uint64"));
394integer_schema!(isize, Some("int64"));
395integer_schema!(usize, Some("uint64"));
396integer_schema!(i128, None);
397integer_schema!(u128, None);
398
399impl JsonSchema for f32 {
400    fn schema() -> Schema {
401        Schema::number(Some("float"))
402    }
403}
404
405impl JsonSchema for &str {
406    fn schema() -> Schema {
407        Schema::string()
408    }
409}
410
411impl JsonSchema for () {
412    fn schema() -> Schema {
413        Schema::Primitive(PrimitiveSchema {
414            schema_type: SchemaType::Null,
415            format: None,
416            nullable: false,
417        })
418    }
419}
420
421impl JsonSchema for serde_json::Value {
422    fn schema() -> Schema {
423        Schema::Boolean(true)
424    }
425}
426
427impl<T: JsonSchema, S: std::hash::BuildHasher> JsonSchema for HashMap<String, T, S> {
428    fn schema() -> Schema {
429        Schema::Object(ObjectSchema {
430            additional_properties: Some(Box::new(T::schema())),
431            ..ObjectSchema::default()
432        })
433    }
434}
435
436impl<T: JsonSchema> JsonSchema for std::collections::BTreeMap<String, T> {
437    fn schema() -> Schema {
438        <HashMap<String, T>>::schema()
439    }
440}
441
442impl<T: JsonSchema> JsonSchema for Option<T> {
443    fn schema() -> Schema {
444        T::schema().nullable()
445    }
446}
447
448impl<T: JsonSchema> JsonSchema for Vec<T> {
449    fn schema() -> Schema {
450        Schema::Array(ArraySchema {
451            items: Box::new(T::schema()),
452            min_items: None,
453            max_items: None,
454        })
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn bounded_array_uses_json_schema_keywords_and_round_trips() {
464        let schema = Schema::Array(ArraySchema {
465            items: Box::new(Schema::integer(None)),
466            min_items: Some(2),
467            max_items: Some(4),
468        });
469        let json = serde_json::to_value(schema).unwrap();
470        assert_eq!(json["type"], "array");
471        assert_eq!(json["minItems"], 2);
472        assert_eq!(json["maxItems"], 4);
473        assert!(json["min_items"].is_null());
474        assert!(json["max_items"].is_null());
475        let decoded: Schema = serde_json::from_value(json.clone()).unwrap();
476        assert!(
477            matches!(&decoded, Schema::Array(array) if array.min_items == Some(2) && array.max_items == Some(4))
478        );
479        assert_eq!(serde_json::to_value(decoded).unwrap(), json);
480    }
481
482    #[test]
483    fn optional_array_schema_accepts_real_null_and_retains_item_type() {
484        let json = serde_json::to_value(<Option<Vec<String>>>::schema()).unwrap();
485        assert_eq!(json["anyOf"][0]["type"], "array");
486        assert_eq!(json["anyOf"][0]["items"]["type"], "string");
487        assert_eq!(json["anyOf"][1]["type"], "null");
488        let decoded: Schema = serde_json::from_value(json.clone()).unwrap();
489        assert!(matches!(&decoded, Schema::AnyOf(_)));
490        assert_eq!(serde_json::to_value(decoded).unwrap(), json);
491    }
492
493    #[test]
494    fn nullable_unions_allow_overlapping_null_branches() {
495        let any_json = serde_json::to_value(<Option<serde_json::Value>>::schema()).unwrap();
496        assert_eq!(any_json["anyOf"][0], true);
497        assert_eq!(any_json["anyOf"][1]["type"], "null");
498        assert!(any_json["oneOf"].is_null());
499        let nested = serde_json::to_value(<Option<Option<Vec<String>>>>::schema()).unwrap();
500        assert_eq!(nested["anyOf"][0]["anyOf"][1]["type"], "null");
501        assert_eq!(nested["anyOf"][1]["type"], "null");
502        let null = serde_json::to_value(<Option<()>>::schema()).unwrap();
503        assert_eq!(null["anyOf"][0]["type"], "null");
504        assert_eq!(null["anyOf"][1]["type"], "null");
505    }
506}