swagger_model.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. # Asterisk -- An open source telephony toolkit.
  2. #
  3. # Copyright (C) 2013, Digium, Inc.
  4. #
  5. # David M. Lee, II <dlee@digium.com>
  6. #
  7. # See http://www.asterisk.org for more information about
  8. # the Asterisk project. Please do not directly contact
  9. # any of the maintainers of this project for assistance;
  10. # the project provides a web site, mailing lists and IRC
  11. # channels for your use.
  12. #
  13. # This program is free software, distributed under the terms of
  14. # the GNU General Public License Version 2. See the LICENSE file
  15. # at the top of the source tree.
  16. #
  17. """Swagger data model objects.
  18. These objects should map directly to the Swagger api-docs, without a lot of
  19. additional fields. In the process of translation, it should also validate the
  20. model for consistency against the Swagger spec (i.e., fail if fields are
  21. missing, or have incorrect values).
  22. See https://github.com/wordnik/swagger-core/wiki/API-Declaration for the spec.
  23. """
  24. from __future__ import print_function
  25. import json
  26. import os.path
  27. import pprint
  28. import re
  29. import sys
  30. import traceback
  31. # We don't fully support Swagger 1.2, but we need it for subtyping
  32. SWAGGER_VERSIONS = ["1.1", "1.2"]
  33. SWAGGER_PRIMITIVES = [
  34. 'void',
  35. 'string',
  36. 'boolean',
  37. 'number',
  38. 'int',
  39. 'long',
  40. 'double',
  41. 'float',
  42. 'Date',
  43. ]
  44. class Stringify(object):
  45. """Simple mix-in to make the repr of the model classes more meaningful.
  46. """
  47. def __repr__(self):
  48. return "%s(%s)" % (self.__class__, pprint.saferepr(self.__dict__))
  49. def compare_versions(lhs, rhs):
  50. '''Performs a lexicographical comparison between two version numbers.
  51. This properly handles simple major.minor.whatever.sure.why.not version
  52. numbers, but fails miserably if there's any letters in there.
  53. For reference:
  54. 1.0 == 1.0
  55. 1.0 < 1.0.1
  56. 1.2 < 1.10
  57. @param lhs Left hand side of the comparison
  58. @param rhs Right hand side of the comparison
  59. @return < 0 if lhs < rhs
  60. @return == 0 if lhs == rhs
  61. @return > 0 if lhs > rhs
  62. '''
  63. lhs = [int(v) for v in lhs.split('.')]
  64. rhs = [int(v) for v in rhs.split('.')]
  65. return (lhs > rhs) - (lhs < rhs)
  66. class ParsingContext(object):
  67. """Context information for parsing.
  68. This object is immutable. To change contexts (like adding an item to the
  69. stack), use the next() and next_stack() functions to build a new one.
  70. """
  71. def __init__(self, swagger_version, stack):
  72. self.__swagger_version = swagger_version
  73. self.__stack = stack
  74. def __repr__(self):
  75. return "ParsingContext(swagger_version=%s, stack=%s)" % (
  76. self.swagger_version, self.stack)
  77. def get_swagger_version(self):
  78. return self.__swagger_version
  79. def get_stack(self):
  80. return self.__stack
  81. swagger_version = property(get_swagger_version)
  82. stack = property(get_stack)
  83. def version_less_than(self, ver):
  84. return compare_versions(self.swagger_version, ver) < 0
  85. def next_stack(self, json, id_field):
  86. """Returns a new item pushed to the stack.
  87. @param json: Current JSON object.
  88. @param id_field: Field identifying this object.
  89. @return New context with additional item in the stack.
  90. """
  91. if not id_field in json:
  92. raise SwaggerError("Missing id_field: %s" % id_field, self)
  93. new_stack = self.stack + ['%s=%s' % (id_field, str(json[id_field]))]
  94. return ParsingContext(self.swagger_version, new_stack)
  95. def next(self, version=None, stack=None):
  96. if version is None:
  97. version = self.version
  98. if stack is None:
  99. stack = self.stack
  100. return ParsingContext(version, stack)
  101. class SwaggerError(Exception):
  102. """Raised when an error is encountered mapping the JSON objects into the
  103. model.
  104. """
  105. def __init__(self, msg, context, cause=None):
  106. """Ctor.
  107. @param msg: String message for the error.
  108. @param context: ParsingContext object
  109. @param cause: Optional exception that caused this one.
  110. """
  111. super(Exception, self).__init__(msg, context, cause)
  112. class SwaggerPostProcessor(object):
  113. """Post processing interface for model objects. This processor can add
  114. fields to model objects for additional information to use in the
  115. templates.
  116. """
  117. def process_resource_api(self, resource_api, context):
  118. """Post process a ResourceApi object.
  119. @param resource_api: ResourceApi object.
  120. @param context: Current context in the API.
  121. """
  122. pass
  123. def process_api(self, api, context):
  124. """Post process an Api object.
  125. @param api: Api object.
  126. @param context: Current context in the API.
  127. """
  128. pass
  129. def process_operation(self, operation, context):
  130. """Post process a Operation object.
  131. @param operation: Operation object.
  132. @param context: Current context in the API.
  133. """
  134. pass
  135. def process_parameter(self, parameter, context):
  136. """Post process a Parameter object.
  137. @param parameter: Parameter object.
  138. @param context: Current context in the API.
  139. """
  140. pass
  141. def process_model(self, model, context):
  142. """Post process a Model object.
  143. @param model: Model object.
  144. @param context: Current context in the API.
  145. """
  146. pass
  147. def process_property(self, property, context):
  148. """Post process a Property object.
  149. @param property: Property object.
  150. @param context: Current context in the API.
  151. """
  152. pass
  153. def process_type(self, swagger_type, context):
  154. """Post process a SwaggerType object.
  155. @param swagger_type: ResourceListing object.
  156. @param context: Current context in the API.
  157. """
  158. pass
  159. def process_resource_listing(self, resource_listing, context):
  160. """Post process the overall ResourceListing object.
  161. @param resource_listing: ResourceListing object.
  162. @param context: Current context in the API.
  163. """
  164. pass
  165. class AllowableRange(Stringify):
  166. """Model of a allowableValues of type RANGE
  167. See https://github.com/wordnik/swagger-core/wiki/datatypes#complex-types
  168. """
  169. def __init__(self, min_value, max_value):
  170. self.min_value = min_value
  171. self.max_value = max_value
  172. def to_wiki(self):
  173. return "Allowed range: Min: {0}; Max: {1}".format(self.min_value, self.max_value)
  174. class AllowableList(Stringify):
  175. """Model of a allowableValues of type LIST
  176. See https://github.com/wordnik/swagger-core/wiki/datatypes#complex-types
  177. """
  178. def __init__(self, values):
  179. self.values = values
  180. def to_wiki(self):
  181. return "Allowed values: {0}".format(", ".join(self.values))
  182. def load_allowable_values(json, context):
  183. """Parse a JSON allowableValues object.
  184. This returns None, AllowableList or AllowableRange, depending on the
  185. valueType in the JSON. If the valueType is not recognized, a SwaggerError
  186. is raised.
  187. """
  188. if not json:
  189. return None
  190. if not 'valueType' in json:
  191. raise SwaggerError("Missing valueType field", context)
  192. value_type = json['valueType']
  193. if value_type == 'RANGE':
  194. if not 'min' in json and not 'max' in json:
  195. raise SwaggerError("Missing fields min/max", context)
  196. return AllowableRange(json.get('min'), json.get('max'))
  197. if value_type == 'LIST':
  198. if not 'values' in json:
  199. raise SwaggerError("Missing field values", context)
  200. return AllowableList(json['values'])
  201. raise SwaggerError("Unkown valueType %s" % value_type, context)
  202. class Parameter(Stringify):
  203. """Model of an operation's parameter.
  204. See https://github.com/wordnik/swagger-core/wiki/parameters
  205. """
  206. required_fields = ['name', 'paramType', 'dataType']
  207. def __init__(self):
  208. self.param_type = None
  209. self.name = None
  210. self.description = None
  211. self.data_type = None
  212. self.required = None
  213. self.allowable_values = None
  214. self.allow_multiple = None
  215. def load(self, parameter_json, processor, context):
  216. context = context.next_stack(parameter_json, 'name')
  217. validate_required_fields(parameter_json, self.required_fields, context)
  218. self.name = parameter_json.get('name')
  219. self.param_type = parameter_json.get('paramType')
  220. self.description = parameter_json.get('description') or ''
  221. self.data_type = parameter_json.get('dataType')
  222. self.required = parameter_json.get('required') or False
  223. self.default_value = parameter_json.get('defaultValue')
  224. self.allowable_values = load_allowable_values(
  225. parameter_json.get('allowableValues'), context)
  226. self.allow_multiple = parameter_json.get('allowMultiple') or False
  227. processor.process_parameter(self, context)
  228. if parameter_json.get('allowedValues'):
  229. raise SwaggerError(
  230. "Field 'allowedValues' invalid; use 'allowableValues'",
  231. context)
  232. return self
  233. def is_type(self, other_type):
  234. return self.param_type == other_type
  235. class ErrorResponse(Stringify):
  236. """Model of an error response.
  237. See https://github.com/wordnik/swagger-core/wiki/errors
  238. """
  239. required_fields = ['code', 'reason']
  240. def __init__(self):
  241. self.code = None
  242. self.reason = None
  243. def load(self, err_json, processor, context):
  244. context = context.next_stack(err_json, 'code')
  245. validate_required_fields(err_json, self.required_fields, context)
  246. self.code = err_json.get('code')
  247. self.reason = err_json.get('reason')
  248. return self
  249. class SwaggerType(Stringify):
  250. """Model of a data type.
  251. """
  252. def __init__(self):
  253. self.name = None
  254. self.is_discriminator = None
  255. self.is_list = None
  256. self.singular_name = None
  257. self.is_primitive = None
  258. def load(self, type_name, processor, context):
  259. # Some common errors
  260. if type_name == 'integer':
  261. raise SwaggerError("The type for integer should be 'int'", context)
  262. self.name = type_name
  263. type_param = get_list_parameter_type(self.name)
  264. self.is_list = type_param is not None
  265. if self.is_list:
  266. self.singular_name = type_param
  267. else:
  268. self.singular_name = self.name
  269. self.is_primitive = self.singular_name in SWAGGER_PRIMITIVES
  270. processor.process_type(self, context)
  271. return self
  272. class Operation(Stringify):
  273. """Model of an operation on an API
  274. See https://github.com/wordnik/swagger-core/wiki/API-Declaration#apis
  275. """
  276. required_fields = ['httpMethod', 'nickname', 'responseClass', 'summary']
  277. def __init__(self):
  278. self.http_method = None
  279. self.nickname = None
  280. self.response_class = None
  281. self.parameters = []
  282. self.summary = None
  283. self.notes = None
  284. self.error_responses = []
  285. def load(self, op_json, processor, context):
  286. context = context.next_stack(op_json, 'nickname')
  287. validate_required_fields(op_json, self.required_fields, context)
  288. self.http_method = op_json.get('httpMethod')
  289. self.nickname = op_json.get('nickname')
  290. response_class = op_json.get('responseClass')
  291. self.response_class = response_class and SwaggerType().load(
  292. response_class, processor, context)
  293. # Specifying WebSocket URL's is our own extension
  294. self.is_websocket = op_json.get('upgrade') == 'websocket'
  295. self.is_req = not self.is_websocket
  296. if self.is_websocket:
  297. self.websocket_protocol = op_json.get('websocketProtocol')
  298. if self.http_method != 'GET':
  299. raise SwaggerError(
  300. "upgrade: websocket is only valid on GET operations",
  301. context)
  302. params_json = op_json.get('parameters') or []
  303. self.parameters = [
  304. Parameter().load(j, processor, context) for j in params_json]
  305. self.query_parameters = [
  306. p for p in self.parameters if p.is_type('query')]
  307. self.has_query_parameters = self.query_parameters and True
  308. self.path_parameters = [
  309. p for p in self.parameters if p.is_type('path')]
  310. self.has_path_parameters = self.path_parameters and True
  311. self.header_parameters = [
  312. p for p in self.parameters if p.is_type('header')]
  313. self.has_header_parameters = self.header_parameters and True
  314. self.has_parameters = self.has_query_parameters or \
  315. self.has_path_parameters or self.has_header_parameters
  316. # Body param is different, since there's at most one
  317. self.body_parameter = [
  318. p for p in self.parameters if p.is_type('body')]
  319. if len(self.body_parameter) > 1:
  320. raise SwaggerError("Cannot have more than one body param", context)
  321. self.body_parameter = self.body_parameter and self.body_parameter[0]
  322. self.has_body_parameter = self.body_parameter and True
  323. self.summary = op_json.get('summary')
  324. self.notes = op_json.get('notes')
  325. err_json = op_json.get('errorResponses') or []
  326. self.error_responses = [
  327. ErrorResponse().load(j, processor, context) for j in err_json]
  328. self.has_error_responses = self.error_responses != []
  329. processor.process_operation(self, context)
  330. return self
  331. class Api(Stringify):
  332. """Model of a single API in an API declaration.
  333. See https://github.com/wordnik/swagger-core/wiki/API-Declaration
  334. """
  335. required_fields = ['path', 'operations']
  336. def __init__(self,):
  337. self.path = None
  338. self.description = None
  339. self.operations = []
  340. def load(self, api_json, processor, context):
  341. context = context.next_stack(api_json, 'path')
  342. validate_required_fields(api_json, self.required_fields, context)
  343. self.path = api_json.get('path')
  344. self.description = api_json.get('description')
  345. op_json = api_json.get('operations')
  346. self.operations = [
  347. Operation().load(j, processor, context) for j in op_json]
  348. self.has_websocket = any(op.is_websocket for op in self.operations)
  349. processor.process_api(self, context)
  350. return self
  351. def get_list_parameter_type(type_string):
  352. """Returns the type parameter if the given type_string is List[].
  353. @param type_string: Type string to parse
  354. @returns Type parameter of the list, or None if not a List.
  355. """
  356. list_match = re.match('^List\[(.*)\]$', type_string)
  357. return list_match and list_match.group(1)
  358. class Property(Stringify):
  359. """Model of a Swagger property.
  360. See https://github.com/wordnik/swagger-core/wiki/datatypes
  361. """
  362. required_fields = ['type']
  363. def __init__(self, name):
  364. self.name = name
  365. self.type = None
  366. self.description = None
  367. self.required = None
  368. def load(self, property_json, processor, context):
  369. validate_required_fields(property_json, self.required_fields, context)
  370. # Bit of a hack, but properties do not self-identify
  371. context = context.next_stack({'name': self.name}, 'name')
  372. self.description = property_json.get('description') or ''
  373. self.required = property_json.get('required') or False
  374. type = property_json.get('type')
  375. self.type = type and SwaggerType().load(type, processor, context)
  376. processor.process_property(self, context)
  377. return self
  378. class Model(Stringify):
  379. """Model of a Swagger model.
  380. See https://github.com/wordnik/swagger-core/wiki/datatypes
  381. """
  382. required_fields = ['description', 'properties']
  383. def __init__(self):
  384. self.id = None
  385. self.subtypes = []
  386. self.__subtype_types = []
  387. self.notes = None
  388. self.description = None
  389. self.__properties = None
  390. self.__discriminator = None
  391. self.__extends_type = None
  392. def load(self, id, model_json, processor, context):
  393. context = context.next_stack(model_json, 'id')
  394. validate_required_fields(model_json, self.required_fields, context)
  395. # The duplication of the model's id is required by the Swagger spec.
  396. self.id = model_json.get('id')
  397. if id != self.id:
  398. raise SwaggerError("Model id doesn't match name", context)
  399. self.subtypes = model_json.get('subTypes') or []
  400. if self.subtypes and context.version_less_than("1.2"):
  401. raise SwaggerError("Type extension support added in Swagger 1.2",
  402. context)
  403. self.description = model_json.get('description')
  404. props = model_json.get('properties').items() or []
  405. self.__properties = [
  406. Property(k).load(j, processor, context) for (k, j) in props]
  407. self.__properties = sorted(self.__properties, key=lambda p: p.name)
  408. discriminator = model_json.get('discriminator')
  409. if discriminator:
  410. if context.version_less_than("1.2"):
  411. raise SwaggerError("Discriminator support added in Swagger 1.2",
  412. context)
  413. discr_props = [p for p in self.__properties if p.name == discriminator]
  414. if not discr_props:
  415. raise SwaggerError(
  416. "Discriminator '%s' does not name a property of '%s'" % (
  417. discriminator, self.id),
  418. context)
  419. self.__discriminator = discr_props[0]
  420. self.model_json = json.dumps(model_json,
  421. indent=2, separators=(',', ': '))
  422. processor.process_model(self, context)
  423. return self
  424. def extends(self):
  425. return self.__extends_type and self.__extends_type.id
  426. def set_extends_type(self, extends_type):
  427. self.__extends_type = extends_type
  428. def set_subtype_types(self, subtype_types):
  429. self.__subtype_types = subtype_types
  430. def discriminator(self):
  431. """Returns the discriminator, digging through base types if needed.
  432. """
  433. return self.__discriminator or \
  434. self.__extends_type and self.__extends_type.discriminator()
  435. def properties(self):
  436. base_props = []
  437. if self.__extends_type:
  438. base_props = self.__extends_type.properties()
  439. return base_props + self.__properties
  440. def has_properties(self):
  441. return len(self.properties()) > 0
  442. def all_subtypes(self):
  443. """Returns the full list of all subtypes, including sub-subtypes.
  444. """
  445. res = self.__subtype_types + \
  446. [subsubtypes for subtype in self.__subtype_types
  447. for subsubtypes in subtype.all_subtypes()]
  448. return sorted(res, key=lambda m: m.id)
  449. def has_subtypes(self):
  450. """Returns True if type has any subtypes.
  451. """
  452. return len(self.subtypes) > 0
  453. class ApiDeclaration(Stringify):
  454. """Model class for an API Declaration.
  455. See https://github.com/wordnik/swagger-core/wiki/API-Declaration
  456. """
  457. required_fields = [
  458. 'swaggerVersion', '_author', '_copyright', 'apiVersion', 'basePath',
  459. 'resourcePath', 'apis', 'models'
  460. ]
  461. def __init__(self):
  462. self.swagger_version = None
  463. self.author = None
  464. self.copyright = None
  465. self.api_version = None
  466. self.base_path = None
  467. self.resource_path = None
  468. self.apis = []
  469. self.models = []
  470. def load_file(self, api_declaration_file, processor):
  471. context = ParsingContext(None, [api_declaration_file])
  472. try:
  473. return self.__load_file(api_declaration_file, processor, context)
  474. except SwaggerError:
  475. raise
  476. except Exception as e:
  477. print("Error: ", traceback.format_exc(), file=sys.stderr)
  478. raise SwaggerError(
  479. "Error loading %s" % api_declaration_file, context, e)
  480. def __load_file(self, api_declaration_file, processor, context):
  481. with open(api_declaration_file) as fp:
  482. self.load(json.load(fp), processor, context)
  483. expected_resource_path = '/api-docs/' + \
  484. os.path.basename(api_declaration_file) \
  485. .replace(".json", ".{format}")
  486. if self.resource_path != expected_resource_path:
  487. print("%s != %s" % (self.resource_path, expected_resource_path),
  488. file=sys.stderr)
  489. raise SwaggerError("resourcePath has incorrect value", context)
  490. return self
  491. def load(self, api_decl_json, processor, context):
  492. """Loads a resource from a single Swagger resource.json file.
  493. """
  494. # If the version doesn't match, all bets are off.
  495. self.swagger_version = api_decl_json.get('swaggerVersion')
  496. context = context.next(version=self.swagger_version)
  497. if not self.swagger_version in SWAGGER_VERSIONS:
  498. raise SwaggerError(
  499. "Unsupported Swagger version %s" % self.swagger_version, context)
  500. validate_required_fields(api_decl_json, self.required_fields, context)
  501. self.author = api_decl_json.get('_author')
  502. self.copyright = api_decl_json.get('_copyright')
  503. self.api_version = api_decl_json.get('apiVersion')
  504. self.base_path = api_decl_json.get('basePath')
  505. self.resource_path = api_decl_json.get('resourcePath')
  506. api_json = api_decl_json.get('apis') or []
  507. self.apis = [
  508. Api().load(j, processor, context) for j in api_json]
  509. paths = set()
  510. for api in self.apis:
  511. if api.path in paths:
  512. raise SwaggerError("API with duplicated path: %s" % api.path, context)
  513. paths.add(api.path)
  514. self.has_websocket = any(api.has_websocket for api in self.apis)
  515. models = api_decl_json.get('models').items() or []
  516. self.models = [Model().load(id, json, processor, context)
  517. for (id, json) in models]
  518. self.models = sorted(self.models, key=lambda m: m.id)
  519. # Now link all base/extended types
  520. model_dict = dict((m.id, m) for m in self.models)
  521. for m in self.models:
  522. def link_subtype(name):
  523. res = model_dict.get(name)
  524. if not res:
  525. raise SwaggerError("%s has non-existing subtype %s",
  526. m.id, name)
  527. res.set_extends_type(m)
  528. return res;
  529. if m.subtypes:
  530. m.set_subtype_types([
  531. link_subtype(subtype) for subtype in m.subtypes])
  532. return self
  533. class ResourceApi(Stringify):
  534. """Model of an API listing in the resources.json file.
  535. """
  536. required_fields = ['path', 'description']
  537. def __init__(self):
  538. self.path = None
  539. self.description = None
  540. self.api_declaration = None
  541. def load(self, api_json, processor, context):
  542. context = context.next_stack(api_json, 'path')
  543. validate_required_fields(api_json, self.required_fields, context)
  544. self.path = api_json['path'].replace('{format}', 'json')
  545. self.description = api_json['description']
  546. if not self.path or self.path[0] != '/':
  547. raise SwaggerError("Path must start with /", context)
  548. processor.process_resource_api(self, context)
  549. return self
  550. def load_api_declaration(self, base_dir, processor):
  551. self.file = (base_dir + self.path)
  552. self.api_declaration = ApiDeclaration().load_file(self.file, processor)
  553. processor.process_resource_api(self, [self.file])
  554. class ResourceListing(Stringify):
  555. """Model of Swagger's resources.json file.
  556. """
  557. required_fields = ['apiVersion', 'basePath', 'apis']
  558. def __init__(self):
  559. self.swagger_version = None
  560. self.api_version = None
  561. self.base_path = None
  562. self.apis = None
  563. def load_file(self, resource_file, processor):
  564. context = ParsingContext(None, [resource_file])
  565. try:
  566. return self.__load_file(resource_file, processor, context)
  567. except SwaggerError:
  568. raise
  569. except Exception as e:
  570. print("Error: ", traceback.format_exc(), file=sys.stderr)
  571. raise SwaggerError(
  572. "Error loading %s" % resource_file, context, e)
  573. def __load_file(self, resource_file, processor, context):
  574. with open(resource_file) as fp:
  575. return self.load(json.load(fp), processor, context)
  576. def load(self, resources_json, processor, context):
  577. # If the version doesn't match, all bets are off.
  578. self.swagger_version = resources_json.get('swaggerVersion')
  579. if not self.swagger_version in SWAGGER_VERSIONS:
  580. raise SwaggerError(
  581. "Unsupported Swagger version %s" % self.swagger_version, context)
  582. validate_required_fields(resources_json, self.required_fields, context)
  583. self.api_version = resources_json['apiVersion']
  584. self.base_path = resources_json['basePath']
  585. apis_json = resources_json['apis']
  586. self.apis = [
  587. ResourceApi().load(j, processor, context) for j in apis_json]
  588. processor.process_resource_listing(self, context)
  589. return self
  590. def validate_required_fields(json, required_fields, context):
  591. """Checks a JSON object for a set of required fields.
  592. If any required field is missing, a SwaggerError is raised.
  593. @param json: JSON object to check.
  594. @param required_fields: List of required fields.
  595. @param context: Current context in the API.
  596. """
  597. missing_fields = [f for f in required_fields if not f in json]
  598. if missing_fields:
  599. raise SwaggerError(
  600. "Missing fields: %s" % ', '.join(missing_fields), context)