-
Notifications
You must be signed in to change notification settings - Fork 38
/
marshmallow_to_swagger.py
735 lines (566 loc) · 21.3 KB
/
marshmallow_to_swagger.py
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
"""
Marshmallow to Swagger Conversion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Utilities for converting Marshmallow objects to their
corresponding Swagger representation.
:copyright: Copyright 2018 PlanGrid, Inc., see AUTHORS.
:license: MIT, see LICENSE for details.
"""
import copy
import inspect
import logging
import sys
from collections import namedtuple
from typing import Any, Optional, Type, Union
import marshmallow as m
from marshmallow.validate import Range
from marshmallow.validate import OneOf
from marshmallow.validate import Length
from marshmallow.validate import Validator
from flask_rebar import compat
from flask_rebar.validation import QueryParamList
from flask_rebar.validation import CommaSeparatedList
from flask_rebar.swagger_generation import swagger_words as sw
LoadDumpOptions = None
try:
EnumField: Optional[Type[m.fields.Field]] = m.fields.Enum
except AttributeError:
try:
from marshmallow_enum import EnumField, LoadDumpOptions # type: ignore
except ImportError:
EnumField = None
# Special value to signify that a JSONSchema field should be left unset
class UNSET:
pass
# We'll use this to mark methods as JSONSchema attribute setters
_method_marker = "__sets_jsonschema_attr__"
# Holds attributes that we can pass around in these recursive
# calls to converters. Bit messy, but :shrug:
_Context = namedtuple(
"_Context",
[
# This will hold a reference to a convert method that can be used
# to make recursive calls
"convert",
# Only really using this for validators at the moment. It will hold the
# JSONSchema object that's been converter so far, so that the validator
# can be converted based on the type of the schema.
"memo",
# The current schema being converted.
"schema",
# The major version of OpenAPI being converter for
"openapi_version",
],
)
class UnregisteredType(Exception):
pass
def _normalize_validate(validate):
"""
Coerces the validate attribute on a Marshmallow field to a consistent type.
The validate attribute on a Marshmallow field can either be a single
Validator or a collection of Validators.
:param Validator|list[Validator] validate:
:rtype: list[Validator]
"""
if callable(validate):
return [validate]
else:
return validate
def get_swagger_title(obj):
"""
Gets a title for the given object. This title will be used
as a name/key for the object in swagger.
:param obj:
:rtype: str
"""
if hasattr(obj, "__swagger_title__"):
return obj.__swagger_title__
elif hasattr(obj, "__name__"):
return obj.__name__
else:
return obj.__class__.__name__
def sets_swagger_attr(attr):
"""
Decorates a `MarshmallowConverter` method, marking it as an JSONSchema
attribute setter.
Example usage::
class Converter(MarshmallowConverter):
MARSHMALLOW_TYPE = String()
@sets_swagger_attr('type')
def get_type(obj, context):
return 'string'
This converter receives instances of `String` and converts it to a
JSONSchema object that looks like `{'type': 'string'}`.
:param str attr: The attribute to set
"""
def wrapper(f):
setattr(f, _method_marker, attr)
return f
return wrapper
def get_schema_fields(schema):
"""Retrieve all the names and field objects for a marshmallow Schema
:param m.Schema schema:
:returns: Yields tuples of the field name and the field itself
:rtype: typing.Iterator[typing.Tuple[str, m.fields.Field]]
"""
fields = []
for name, field in schema.fields.items():
prop = compat.get_data_key(field)
fields.append((prop, field))
return sorted(fields)
class MarshmallowConverter:
"""
Abstract class for objects that convert Marshmallow objects to
JSONSchema dictionaries.
"""
MARSHMALLOW_TYPE: Any = None
def convert(self, obj, context):
"""
Converts a Marshmallow object to a JSONSchema dictionary.
This inspects the converter instance for methods that have been
marked as attribute setters, calling them to set attributes on the
resulting JSONSchema dictionary.
:param m.Schema|m.fields.Field|Validator obj:
The Marshmallow object to be converted
:param _Context context:
Various information to help the converter understand how to
convert the object.
:rtype: dict
"""
jsonschema_obj = {}
for _, method in inspect.getmembers(self, predicate=inspect.ismethod):
if hasattr(method, _method_marker):
val = method(obj, context)
if val is not UNSET:
jsonschema_obj[getattr(method, _method_marker)] = val
return jsonschema_obj
class SchemaConverter(MarshmallowConverter):
"""Converts Marshmallow Schema objects."""
MARSHMALLOW_TYPE = m.Schema
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
if obj.many:
return sw.array
else:
return sw.object_
@sets_swagger_attr(sw.items)
def get_items(self, obj, context):
if not obj.many:
return UNSET
singular_obj = copy.deepcopy(obj)
singular_obj.many = False
return context.convert(singular_obj, context)
@sets_swagger_attr(sw.properties)
def get_properties(self, obj, context):
if obj.many:
return UNSET
properties = {}
for prop, field in get_schema_fields(obj):
properties[prop] = context.convert(field, context)
return properties
@sets_swagger_attr(sw.required)
def get_required(self, obj, context):
if obj.many or obj.partial is True:
return UNSET
required = []
obj_partial_is_collection = m.utils.is_collection(obj.partial)
for name, field in obj.fields.items():
if field.required:
prop = compat.get_data_key(field)
if obj_partial_is_collection and prop in obj.partial:
continue
required.append(prop)
if required and not obj.ordered:
required = sorted(required)
return required if required else UNSET
@sets_swagger_attr(sw.description)
def get_description(self, obj, context):
if obj.many:
return UNSET
elif obj.__doc__:
return obj.__doc__
else:
return UNSET
@sets_swagger_attr(sw.title)
def get_title(self, obj, context):
if not obj.many:
return get_swagger_title(obj)
else:
return UNSET
@sets_swagger_attr(sw.additional_properties)
def get_additional_properties(self, obj, context):
if obj.unknown in (m.RAISE, m.EXCLUDE):
return False
elif obj.unknown is m.INCLUDE:
return True
else:
raise ValueError(
f"Unexpected Schema.unknown value {obj.unknown} for {obj} "
)
class FieldConverter(MarshmallowConverter):
"""
Base Converter for Marshmallow Field objects.
This should be extended for specific Field types.
"""
MARSHMALLOW_TYPE: Type[m.fields.Field] = m.fields.Field
def convert(self, obj, context):
jsonschema_obj = super().convert(obj, context)
if obj.dump_only:
jsonschema_obj["readOnly"] = True
if obj.validate:
validators = _normalize_validate(obj.validate)
for validator in validators:
try:
jsonschema_obj.update(
context.convert(
obj=validator,
context=_Context(
convert=context.convert,
memo=jsonschema_obj,
schema=context.schema,
openapi_version=context.openapi_version,
),
)
)
except UnregisteredType as e:
logging.debug(
"Unable to convert validator {validator}: {err}".format(
validator=validator, err=e
)
)
return jsonschema_obj
# With OpenApi 3.1 nullable has been removed entirely
# and allowing 'none' means we return an array of allowed types that includes sw.null
def null_type_determination(self, obj, context, sw_type):
if context.openapi_version == 3 and obj.allow_none:
return [sw_type, sw.null]
else:
return sw_type
@sets_swagger_attr(sw.default)
def get_default(self, obj, context):
if (
obj.load_default is not m.missing
# Marshmallow accepts a callable for the default. This is tricky
# to handle, so let's just ignore this for now.
and not callable(obj.load_default)
):
return obj.load_default
else:
return UNSET
@sets_swagger_attr(sw.nullable)
def get_nullable(self, obj, context):
if context.openapi_version == 2 and obj.allow_none is not False:
return True
else:
return UNSET
@sets_swagger_attr(sw.description)
def get_description(self, obj, context):
if "description" in obj.metadata:
return obj.metadata["description"]
else:
return UNSET
class ValidatorConverter(MarshmallowConverter):
"""
Base Converter for Marshmallow Validator objects.
This should be extended for specific Validator types.
"""
MARSHMALLOW_TYPE: Union[Type[Validator], Type[OneOf]] = Validator
class NestedConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Nested
def convert(self, obj, context):
return context.convert(obj.schema, context)
class ListConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.List
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.array)
@sets_swagger_attr(sw.items)
def get_items(self, obj, context):
return context.convert(obj.inner, context)
class DictConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Dict
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.object_)
class IntegerConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Integer
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.integer)
class StringConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.String
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.string)
class NumberConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Number
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.number)
class BooleanConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Boolean
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.boolean)
class DateTimeConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.DateTime
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.string)
@sets_swagger_attr(sw.format_)
def get_format(self, obj, context):
return sw.date_time
class UUIDConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.UUID
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.string)
@sets_swagger_attr(sw.format_)
def get_format(self, obj, context):
return sw.uuid
class DateConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Date
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
return self.null_type_determination(obj, context, sw.string)
@sets_swagger_attr(sw.format_)
def get_format(self, obj, context):
return sw.date
class MethodConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Method
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
if "swagger_type" in obj.metadata:
return self.null_type_determination(
obj, context, obj.metadata["swagger_type"]
)
else:
raise ValueError(
'Must include "swagger_type" ' "keyword argument in Method field"
)
class FunctionConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Function
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
if "swagger_type" in obj.metadata:
return self.null_type_determination(
obj, context, obj.metadata["swagger_type"]
)
else:
raise ValueError(
'Must include "swagger_type" ' "keyword argument in Function field"
)
class ConstantConverter(FieldConverter):
MARSHMALLOW_TYPE = m.fields.Constant
@sets_swagger_attr(sw.enum)
def get_enum(self, obj, context):
return [obj.constant]
class CsvArrayConverter(ListConverter):
MARSHMALLOW_TYPE = CommaSeparatedList
@sets_swagger_attr(sw.collection_format)
def get_collection_format(self, obj, context):
return sw.csv if context.openapi_version == 2 else UNSET
@sets_swagger_attr(sw.style)
def get_style(self, obj, context):
return sw.form if context.openapi_version == 3 else UNSET
@sets_swagger_attr(sw.explode)
def get_explode(self, obj, context):
return False if context.openapi_version == 3 else UNSET
class MultiArrayConverter(ListConverter):
MARSHMALLOW_TYPE = QueryParamList
@sets_swagger_attr(sw.collection_format)
def get_collection_format(self, obj, context):
return sw.multi if context.openapi_version == 2 else UNSET
@sets_swagger_attr(sw.explode)
def get_explode(self, obj, context):
return True if context.openapi_version == 3 else UNSET
class RangeConverter(ValidatorConverter):
MARSHMALLOW_TYPE = Range
@sets_swagger_attr(sw.minimum)
def get_minimum(self, obj, context):
if obj.min is not None:
return obj.min
else:
return UNSET
@sets_swagger_attr(sw.maximum)
def get_maximum(self, obj, context):
if obj.max is not None:
return obj.max
else:
return UNSET
class OneOfConverter(ValidatorConverter):
MARSHMALLOW_TYPE = OneOf
@sets_swagger_attr(sw.enum)
def get_enum(self, obj, context):
return list(obj.choices)
class LengthConverter(ValidatorConverter):
MARSHMALLOW_TYPE = Length
@sets_swagger_attr(sw.min_items)
def get_minimum_items(self, obj, context):
if context.memo[sw.type_] == sw.array:
if obj.min is not None:
return obj.min
return UNSET
@sets_swagger_attr(sw.max_items)
def get_maximum_items(self, obj, context):
if context.memo[sw.type_] == sw.array:
if obj.max is not None:
return obj.max
return UNSET
@sets_swagger_attr(sw.min_length)
def get_minimum_length(self, obj, context):
if context.memo[sw.type_] == sw.string:
if obj.min is not None:
return obj.min
return UNSET
@sets_swagger_attr(sw.max_length)
def get_maximum_length(self, obj, context):
if context.memo[sw.type_] == sw.string:
if obj.max is not None:
return obj.max
return UNSET
class ConverterRegistry:
"""
Registry for MarshmallowConverters.
Schemas for responses, query strings, request bodies, etc. need to
be converted differently. For example, response schemas as "dump"ed and
request body schemas are "loaded". For another example, query strings
don't support nesting.
This registry also allows for additional converters to be added for custom
Marshmallow types.
"""
def __init__(self):
self._type_map = {}
self._validator_map = {}
def register_type(self, converter):
"""
Registers a converter.
:param MarshmallowConverter converter:
"""
self._type_map[converter.MARSHMALLOW_TYPE] = converter
def register_types(self, converters):
"""
Registers multiple converters.
:param iterable[MarshmallowConverter] converters:
"""
for converter in converters:
self.register_type(converter)
def _get_converter_for_type(self, obj):
"""
Locates the registered converter for a given type.
:param obj: instance to convert
:return: converter for type of instance
"""
method_resolution_order = obj.__class__.__mro__
for cls in method_resolution_order:
if cls in self._type_map:
return self._type_map[cls]
else:
raise UnregisteredType(
"No registered type found in method resolution order: {mro}\n"
"Registered types: {types}".format(
mro=method_resolution_order, types=list(self._type_map.keys())
)
)
def _convert(self, obj, context):
"""
Converts a Marshmallow object to a JSONSchema dictionary.
:param m.Schema|m.fields.Field|Validator obj:
The Marshmallow object to be converted
:param _Context context:
Various information to help the converter understand how to
convert the given object.
This helps with all the recursive nonsense.
:rtype: dict
"""
return self._get_converter_for_type(obj).convert(obj=obj, context=context)
def convert(self, obj, openapi_version=2):
"""
Converts a Marshmallow object to a JSONSchema dictionary.
:param m.Schema|m.fields.Field|Validator obj:
The Marshmallow object to be converted
:param int openapi_version: major version of OpenAPI to convert obj for
:rtype: dict
"""
return self._convert(
obj=obj,
context=_Context(
convert=self._convert,
memo={},
schema=obj,
openapi_version=openapi_version,
),
)
class EnumConverter(FieldConverter):
MARSHMALLOW_TYPE = EnumField # type: ignore
@sets_swagger_attr(sw.type_)
def get_type(self, obj, context):
# Note: we don't (yet?) support mix-and-match between load_by and dump_by. Pick one.
if obj.by_value or (
LoadDumpOptions is not None
and obj.load_by == obj.dump_by == LoadDumpOptions.value
):
# I'm going out on a limb and assuming your enum uses same type for all vals, else caveat emptor:
value_type = type(next(iter(obj.enum)).value)
if value_type is int:
return self.null_type_determination(obj, context, sw.integer)
elif value_type is float:
return self.null_type_determination(obj, context, sw.number)
else:
return self.null_type_determination(obj, context, sw.string)
else:
return self.null_type_determination(obj, context, sw.string)
@sets_swagger_attr(sw.enum)
def get_enum(self, obj, context):
if obj.by_value or (
LoadDumpOptions is not None
and obj.load_by == obj.dump_by == LoadDumpOptions.value
):
return [entry.value for entry in obj.enum]
else:
return [entry.name for entry in obj.enum]
ALL_CONVERTERS = tuple(
[
klass()
for _, klass in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if issubclass(klass, MarshmallowConverter)
]
)
def _common_converters():
"""Instantiates the converters we use in ALL of the registries below"""
converters = [
BooleanConverter(),
DateConverter(),
DateTimeConverter(),
FunctionConverter(),
IntegerConverter(),
LengthConverter(),
ListConverter(),
MethodConverter(),
NumberConverter(),
OneOfConverter(),
RangeConverter(),
SchemaConverter(),
StringConverter(),
UUIDConverter(),
ConstantConverter(),
]
if EnumConverter.MARSHMALLOW_TYPE is not None:
converters.append(EnumConverter())
return converters
query_string_converter_registry = ConverterRegistry()
query_string_converter_registry.register_types(
_common_converters() + [CsvArrayConverter(), MultiArrayConverter()]
)
headers_converter_registry = ConverterRegistry()
headers_converter_registry.register_types(
_common_converters() + [CsvArrayConverter(), MultiArrayConverter()]
)
request_body_converter_registry = ConverterRegistry()
request_body_converter_registry.register_types(
_common_converters() + [DictConverter(), NestedConverter()]
)
response_converter_registry = ConverterRegistry()
response_converter_registry.register_types(
_common_converters() + [DictConverter(), NestedConverter()]
)