swagger_model.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. import json
  25. import os.path
  26. import pprint
  27. import re
  28. import sys
  29. import traceback
  30. # We don't fully support Swagger 1.2, but we need it for subtyping
  31. SWAGGER_VERSIONS = ["1.1", "1.2"]
  32. SWAGGER_PRIMITIVES = [
  33. 'void',
  34. 'string',
  35. 'boolean',
  36. 'number',
  37. 'int',
  38. 'long',
  39. 'double',
  40. 'float',
  41. 'Date',
  42. ]
  43. class Stringify(object):
  44. """Simple mix-in to make the repr of the model classes more meaningful.
  45. """
  46. def __repr__(self):
  47. return "%s(%s)" % (self.__class__, pprint.saferepr(self.__dict__))
  48. def compare_versions(lhs, rhs):
  49. '''Performs a lexicographical comparison between two version numbers.
  50. This properly handles simple major.minor.whatever.sure.why.not version
  51. numbers, but fails miserably if there's any letters in there.
  52. For reference:
  53. 1.0 == 1.0
  54. 1.0 < 1.0.1
  55. 1.2 < 1.10
  56. @param lhs Left hand side of the comparison
  57. @param rhs Right hand side of the comparison
  58. @return < 0 if lhs < rhs
  59. @return == 0 if lhs == rhs
  60. @return > 0 if lhs > rhs
  61. '''
  62. lhs = [int(v) for v in lhs.split('.')]
  63. rhs = [int(v) for v in rhs.split('.')]
  64. return cmp(lhs, rhs)
  65. class ParsingContext(object):
  66. """Context information for parsing.
  67. This object is immutable. To change contexts (like adding an item to the
  68. stack), use the next() and next_stack() functions to build a new one.
  69. """
  70. def __init__(self, swagger_version, stack):
  71. self.__swagger_version = swagger_version
  72. self.__stack = stack
  73. def __repr__(self):
  74. return "ParsingContext(swagger_version=%s, stack=%s)" % (
  75. self.swagger_version, self.stack)
  76. def get_swagger_version(self):
  77. return self.__swagger_version
  78. def get_stack(self):
  79. return self.__stack
  80. swagger_version = property(get_swagger_version)
  81. stack = property(get_stack)
  82. def version_less_than(self, ver):
  83. return compare_versions(self.swagger_version, ver) < 0
  84. def next_stack(self, json, id_field):
  85. """Returns a new item pushed to the stack.
  86. @param json: Current JSON object.
  87. @param id_field: Field identifying this object.
  88. @return New context with additional item in the stack.
  89. """
  90. if not id_field in json:
  91. raise SwaggerError("Missing id_field: %s" % id_field, self)
  92. new_stack = self.stack + ['%s=%s' % (id_field, str(json[id_field]))]
  93. return ParsingContext(self.swagger_version, new_stack)
  94. def next(self, version=None, stack=None):
  95. if version is None:
  96. version = self.version
  97. if stack is None:
  98. stack = self.stack
  99. return ParsingContext(version, stack)
  100. class SwaggerError(Exception):
  101. """Raised when an error is encountered mapping the JSON objects into the
  102. model.
  103. """
  104. def __init__(self, msg, context, cause=None):
  105. """Ctor.
  106. @param msg: String message for the error.
  107. @param context: ParsingContext object
  108. @param cause: Optional exception that caused this one.
  109. """
  110. super(Exception, self).__init__(msg, context, cause)
  111. class SwaggerPostProcessor(object):
  112. """Post processing interface for model objects. This processor can add
  113. fields to model objects for additional information to use in the
  114. templates.
  115. """
  116. def process_resource_api(self, resource_api, context):
  117. """Post process a ResourceApi object.
  118. @param resource_api: ResourceApi object.
  119. @param context: Current context in the API.
  120. """
  121. pass
  122. def process_api(self, api, context):
  123. """Post process an Api object.
  124. @param api: Api object.
  125. @param context: Current context in the API.
  126. """
  127. pass
  128. def process_operation(self, operation, context):
  129. """Post process a Operation object.
  130. @param operation: Operation object.
  131. @param context: Current context in the API.
  132. """
  133. pass
  134. def process_parameter(self, parameter, context):
  135. """Post process a Parameter object.
  136. @param parameter: Parameter object.
  137. @param context: Current context in the API.
  138. """
  139. pass
  140. def process_model(self, model, context):
  141. """Post process a Model object.
  142. @param model: Model object.
  143. @param context: Current context in the API.
  144. """
  145. pass
  146. def process_property(self, property, context):
  147. """Post process a Property object.
  148. @param property: Property object.
  149. @param context: Current context in the API.
  150. """
  151. pass
  152. def process_type(self, swagger_type, context):
  153. """Post process a SwaggerType object.
  154. @param swagger_type: ResourceListing object.
  155. @param context: Current context in the API.
  156. """
  157. pass
  158. def process_resource_listing(self, resource_listing, context):
  159. """Post process the overall ResourceListing object.
  160. @param resource_listing: ResourceListing object.
  161. @param context: Current context in the API.
  162. """
  163. pass
  164. class AllowableRange(Stringify):
  165. """Model of a allowableValues of type RANGE
  166. See https://github.com/wordnik/swagger-core/wiki/datatypes#complex-types
  167. """
  168. def __init__(self, min_value, max_value):
  169. self.min_value = min_value
  170. self.max_value = max_value
  171. def to_wiki(self):
  172. return "Allowed range: Min: {0}; Max: {1}".format(self.min_value, self.max_value)
  173. class AllowableList(Stringify):
  174. """Model of a allowableValues of type LIST
  175. See https://github.com/wordnik/swagger-core/wiki/datatypes#complex-types
  176. """
  177. def __init__(self, values):
  178. self.values = values
  179. def to_wiki(self):
  180. return "Allowed values: {0}".format(", ".join(self.values))
  181. def load_allowable_values(json, context):
  182. """Parse a JSON allowableValues object.
  183. This returns None, AllowableList or AllowableRange, depending on the
  184. valueType in the JSON. If the valueType is not recognized, a SwaggerError
  185. is raised.
  186. """
  187. if not json:
  188. return None
  189. if not 'valueType' in json:
  190. raise SwaggerError("Missing valueType field", context)
  191. value_type = json['valueType']
  192. if value_type == 'RANGE':
  193. if not 'min' in json and not 'max' in json:
  194. raise SwaggerError("Missing fields min/max", context)
  195. return AllowableRange(json.get('min'), json.get('max'))
  196. if value_type == 'LIST':
  197. if not 'values' in json:
  198. raise SwaggerError("Missing field values", context)
  199. return AllowableList(json['values'])
  200. raise SwaggerError("Unkown valueType %s" % value_type, context)
  201. class Parameter(Stringify):
  202. """Model of an operation's parameter.
  203. See https://github.com/wordnik/swagger-core/wiki/parameters
  204. """
  205. required_fields = ['name', 'paramType', 'dataType']
  206. def __init__(self):
  207. self.param_type = None
  208. self.name = None
  209. self.description = None
  210. self.data_type = None
  211. self.required = None
  212. self.allowable_values = None
  213. self.allow_multiple = None
  214. def load(self, parameter_json, processor, context):
  215. context = context.next_stack(parameter_json, 'name')
  216. validate_required_fields(parameter_json, self.required_fields, context)
  217. self.name = parameter_json.get('name')
  218. self.param_type = parameter_json.get('paramType')
  219. self.description = parameter_json.get('description') or ''
  220. self.data_type = parameter_json.get('dataType')
  221. self.required = parameter_json.get('required') or False
  222. self.default_value = parameter_json.get('defaultValue')
  223. self.allowable_values = load_allowable_values(
  224. parameter_json.get('allowableValues'), context)
  225. self.allow_multiple = parameter_json.get('allowMultiple') or False
  226. processor.process_parameter(self, context)
  227. if parameter_json.get('allowedValues'):
  228. raise SwaggerError(
  229. "Field 'allowedValues' invalid; use 'allowableValues'",
  230. context)
  231. return self
  232. def is_type(self, other_type):
  233. return self.param_type == other_type
  234. class ErrorResponse(Stringify):
  235. """Model of an error response.
  236. See https://github.com/wordnik/swagger-core/wiki/errors
  237. """
  238. required_fields = ['code', 'reason']
  239. def __init__(self):
  240. self.code = None
  241. self.reason = None
  242. def load(self, err_json, processor, context):
  243. context = context.next_stack(err_json, 'code')
  244. validate_required_fields(err_json, self.required_fields, context)
  245. self.code = err_json.get('code')
  246. self.reason = err_json.get('reason')
  247. return self
  248. class SwaggerType(Stringify):
  249. """Model of a data type.
  250. """
  251. def __init__(self):
  252. self.name = None
  253. self.is_discriminator = None
  254. self.is_list = None
  255. self.singular_name = None
  256. self.is_primitive = None
  257. def load(self, type_name, processor, context):
  258. # Some common errors
  259. if type_name == 'integer':
  260. raise SwaggerError("The type for integer should be 'int'", context)
  261. self.name = type_name
  262. type_param = get_list_parameter_type(self.name)
  263. self.is_list = type_param is not None
  264. if self.is_list:
  265. self.singular_name = type_param
  266. else:
  267. self.singular_name = self.name
  268. self.is_primitive = self.singular_name in SWAGGER_PRIMITIVES
  269. processor.process_type(self, context)
  270. return self
  271. class Operation(Stringify):
  272. """Model of an operation on an API
  273. See https://github.com/wordnik/swagger-core/wiki/API-Declaration#apis
  274. """
  275. required_fields = ['httpMethod', 'nickname', 'responseClass', 'summary']
  276. def __init__(self):
  277. self.http_method = None
  278. self.nickname = None
  279. self.response_class = None
  280. self.parameters = []
  281. self.summary = None
  282. self.notes = None
  283. self.error_responses = []
  284. def load(self, op_json, processor, context):
  285. context = context.next_stack(op_json, 'nickname')
  286. validate_required_fields(op_json, self.required_fields, context)
  287. self.http_method = op_json.get('httpMethod')
  288. self.nickname = op_json.get('nickname')
  289. response_class = op_json.get('responseClass')
  290. self.response_class = response_class and SwaggerType().load(
  291. response_class, processor, context)
  292. # Specifying WebSocket URL's is our own extension
  293. self.is_websocket = op_json.get('upgrade') == 'websocket'
  294. self.is_req = not self.is_websocket
  295. if self.is_websocket:
  296. self.websocket_protocol = op_json.get('websocketProtocol')
  297. if self.http_method != 'GET':
  298. raise SwaggerError(
  299. "upgrade: websocket is only valid on GET operations",
  300. context)
  301. params_json = op_json.get('parameters') or []
  302. self.parameters = [
  303. Parameter().load(j, processor, context) for j in params_json]
  304. self.query_parameters = [
  305. p for p in self.parameters if p.is_type('query')]
  306. self.has_query_parameters = self.query_parameters and True
  307. self.path_parameters = [
  308. p for p in self.parameters if p.is_type('path')]
  309. self.has_path_parameters = self.path_parameters and True
  310. self.header_parameters = [
  311. p for p in self.parameters if p.is_type('header')]
  312. self.has_header_parameters = self.header_parameters and True
  313. self.has_parameters = self.has_query_parameters or \
  314. self.has_path_parameters or self.has_header_parameters
  315. # Body param is different, since there's at most one
  316. self.body_parameter = [
  317. p for p in self.parameters if p.is_type('body')]
  318. if len(self.body_parameter) > 1:
  319. raise SwaggerError("Cannot have more than one body param", context)
  320. self.body_parameter = self.body_parameter and self.body_parameter[0]
  321. self.has_body_parameter = self.body_parameter and True
  322. self.summary = op_json.get('summary')
  323. self.notes = op_json.get('notes')
  324. err_json = op_json.get('errorResponses') or []
  325. self.error_responses = [
  326. ErrorResponse().load(j, processor, context) for j in err_json]
  327. self.has_error_responses = self.error_responses != []
  328. processor.process_operation(self, context)
  329. return self
  330. class Api(Stringify):
  331. """Model of a single API in an API declaration.
  332. See https://github.com/wordnik/swagger-core/wiki/API-Declaration
  333. """
  334. required_fields = ['path', 'operations']
  335. def __init__(self,):
  336. self.path = None
  337. self.description = None
  338. self.operations = []
  339. def load(self, api_json, processor, context):
  340. context = context.next_stack(api_json, 'path')
  341. validate_required_fields(api_json, self.required_fields, context)
  342. self.path = api_json.get('path')
  343. self.description = api_json.get('description')
  344. op_json = api_json.get('operations')
  345. self.operations = [
  346. Operation().load(j, processor, context) for j in op_json]
  347. self.has_websocket = \
  348. filter(lambda op: op.is_websocket, 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 >> sys.stderr, "Error: ", traceback.format_exc()
  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 >> sys.stderr, \
  488. "%s != %s" % (self.resource_path, expected_resource_path)
  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 = filter(lambda api: api.has_websocket,
  515. self.apis) == []
  516. models = api_decl_json.get('models').items() or []
  517. self.models = [Model().load(id, json, processor, context)
  518. for (id, json) in models]
  519. self.models = sorted(self.models, key=lambda m: m.id)
  520. # Now link all base/extended types
  521. model_dict = dict((m.id, m) for m in self.models)
  522. for m in self.models:
  523. def link_subtype(name):
  524. res = model_dict.get(subtype)
  525. if not res:
  526. raise SwaggerError("%s has non-existing subtype %s",
  527. m.id, name)
  528. res.set_extends_type(m)
  529. return res;
  530. if m.subtypes:
  531. m.set_subtype_types([
  532. link_subtype(subtype) for subtype in m.subtypes])
  533. return self
  534. class ResourceApi(Stringify):
  535. """Model of an API listing in the resources.json file.
  536. """
  537. required_fields = ['path', 'description']
  538. def __init__(self):
  539. self.path = None
  540. self.description = None
  541. self.api_declaration = None
  542. def load(self, api_json, processor, context):
  543. context = context.next_stack(api_json, 'path')
  544. validate_required_fields(api_json, self.required_fields, context)
  545. self.path = api_json['path']
  546. self.description = api_json['description']
  547. if not self.path or self.path[0] != '/':
  548. raise SwaggerError("Path must start with /", context)
  549. processor.process_resource_api(self, context)
  550. return self
  551. def load_api_declaration(self, base_dir, processor):
  552. self.file = (base_dir + self.path).replace('{format}', 'json')
  553. self.api_declaration = ApiDeclaration().load_file(self.file, processor)
  554. processor.process_resource_api(self, [self.file])
  555. class ResourceListing(Stringify):
  556. """Model of Swagger's resources.json file.
  557. """
  558. required_fields = ['apiVersion', 'basePath', 'apis']
  559. def __init__(self):
  560. self.swagger_version = None
  561. self.api_version = None
  562. self.base_path = None
  563. self.apis = None
  564. def load_file(self, resource_file, processor):
  565. context = ParsingContext(None, [resource_file])
  566. try:
  567. return self.__load_file(resource_file, processor, context)
  568. except SwaggerError:
  569. raise
  570. except Exception as e:
  571. print >> sys.stderr, "Error: ", traceback.format_exc()
  572. raise SwaggerError(
  573. "Error loading %s" % resource_file, context, e)
  574. def __load_file(self, resource_file, processor, context):
  575. with open(resource_file) as fp:
  576. return self.load(json.load(fp), processor, context)
  577. def load(self, resources_json, processor, context):
  578. # If the version doesn't match, all bets are off.
  579. self.swagger_version = resources_json.get('swaggerVersion')
  580. if not self.swagger_version in SWAGGER_VERSIONS:
  581. raise SwaggerError(
  582. "Unsupported Swagger version %s" % swagger_version, context)
  583. validate_required_fields(resources_json, self.required_fields, context)
  584. self.api_version = resources_json['apiVersion']
  585. self.base_path = resources_json['basePath']
  586. apis_json = resources_json['apis']
  587. self.apis = [
  588. ResourceApi().load(j, processor, context) for j in apis_json]
  589. processor.process_resource_listing(self, context)
  590. return self
  591. def validate_required_fields(json, required_fields, context):
  592. """Checks a JSON object for a set of required fields.
  593. If any required field is missing, a SwaggerError is raised.
  594. @param json: JSON object to check.
  595. @param required_fields: List of required fields.
  596. @param context: Current context in the API.
  597. """
  598. missing_fields = [f for f in required_fields if not f in json]
  599. if missing_fields:
  600. raise SwaggerError(
  601. "Missing fields: %s" % ', '.join(missing_fields), context)