swagger_model.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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. class AllowableList(Stringify):
  172. """Model of a allowableValues of type LIST
  173. See https://github.com/wordnik/swagger-core/wiki/datatypes#complex-types
  174. """
  175. def __init__(self, values):
  176. self.values = values
  177. def load_allowable_values(json, context):
  178. """Parse a JSON allowableValues object.
  179. This returns None, AllowableList or AllowableRange, depending on the
  180. valueType in the JSON. If the valueType is not recognized, a SwaggerError
  181. is raised.
  182. """
  183. if not json:
  184. return None
  185. if not 'valueType' in json:
  186. raise SwaggerError("Missing valueType field", context)
  187. value_type = json['valueType']
  188. if value_type == 'RANGE':
  189. if not 'min' in json and not 'max' in json:
  190. raise SwaggerError("Missing fields min/max", context)
  191. return AllowableRange(json.get('min'), json.get('max'))
  192. if value_type == 'LIST':
  193. if not 'values' in json:
  194. raise SwaggerError("Missing field values", context)
  195. return AllowableList(json['values'])
  196. raise SwaggerError("Unkown valueType %s" % value_type, context)
  197. class Parameter(Stringify):
  198. """Model of an operation's parameter.
  199. See https://github.com/wordnik/swagger-core/wiki/parameters
  200. """
  201. required_fields = ['name', 'paramType', 'dataType']
  202. def __init__(self):
  203. self.param_type = None
  204. self.name = None
  205. self.description = None
  206. self.data_type = None
  207. self.required = None
  208. self.allowable_values = None
  209. self.allow_multiple = None
  210. def load(self, parameter_json, processor, context):
  211. context = context.next_stack(parameter_json, 'name')
  212. validate_required_fields(parameter_json, self.required_fields, context)
  213. self.name = parameter_json.get('name')
  214. self.param_type = parameter_json.get('paramType')
  215. self.description = parameter_json.get('description') or ''
  216. self.data_type = parameter_json.get('dataType')
  217. self.required = parameter_json.get('required') or False
  218. self.default_value = parameter_json.get('defaultValue')
  219. self.allowable_values = load_allowable_values(
  220. parameter_json.get('allowableValues'), context)
  221. self.allow_multiple = parameter_json.get('allowMultiple') or False
  222. processor.process_parameter(self, context)
  223. if parameter_json.get('allowedValues'):
  224. raise SwaggerError(
  225. "Field 'allowedValues' invalid; use 'allowableValues'",
  226. context)
  227. return self
  228. def is_type(self, other_type):
  229. return self.param_type == other_type
  230. class ErrorResponse(Stringify):
  231. """Model of an error response.
  232. See https://github.com/wordnik/swagger-core/wiki/errors
  233. """
  234. required_fields = ['code', 'reason']
  235. def __init__(self):
  236. self.code = None
  237. self.reason = None
  238. def load(self, err_json, processor, context):
  239. context = context.next_stack(err_json, 'code')
  240. validate_required_fields(err_json, self.required_fields, context)
  241. self.code = err_json.get('code')
  242. self.reason = err_json.get('reason')
  243. return self
  244. class SwaggerType(Stringify):
  245. """Model of a data type.
  246. """
  247. def __init__(self):
  248. self.name = None
  249. self.is_discriminator = None
  250. self.is_list = None
  251. self.singular_name = None
  252. self.is_primitive = None
  253. def load(self, type_name, processor, context):
  254. # Some common errors
  255. if type_name == 'integer':
  256. raise SwaggerError("The type for integer should be 'int'", context)
  257. self.name = type_name
  258. type_param = get_list_parameter_type(self.name)
  259. self.is_list = type_param is not None
  260. if self.is_list:
  261. self.singular_name = type_param
  262. else:
  263. self.singular_name = self.name
  264. self.is_primitive = self.singular_name in SWAGGER_PRIMITIVES
  265. processor.process_type(self, context)
  266. return self
  267. class Operation(Stringify):
  268. """Model of an operation on an API
  269. See https://github.com/wordnik/swagger-core/wiki/API-Declaration#apis
  270. """
  271. required_fields = ['httpMethod', 'nickname', 'responseClass', 'summary']
  272. def __init__(self):
  273. self.http_method = None
  274. self.nickname = None
  275. self.response_class = None
  276. self.parameters = []
  277. self.summary = None
  278. self.notes = None
  279. self.error_responses = []
  280. def load(self, op_json, processor, context):
  281. context = context.next_stack(op_json, 'nickname')
  282. validate_required_fields(op_json, self.required_fields, context)
  283. self.http_method = op_json.get('httpMethod')
  284. self.nickname = op_json.get('nickname')
  285. response_class = op_json.get('responseClass')
  286. self.response_class = response_class and SwaggerType().load(
  287. response_class, processor, context)
  288. # Specifying WebSocket URL's is our own extension
  289. self.is_websocket = op_json.get('upgrade') == 'websocket'
  290. self.is_req = not self.is_websocket
  291. if self.is_websocket:
  292. self.websocket_protocol = op_json.get('websocketProtocol')
  293. if self.http_method != 'GET':
  294. raise SwaggerError(
  295. "upgrade: websocket is only valid on GET operations",
  296. context)
  297. params_json = op_json.get('parameters') or []
  298. self.parameters = [
  299. Parameter().load(j, processor, context) for j in params_json]
  300. self.query_parameters = [
  301. p for p in self.parameters if p.is_type('query')]
  302. self.has_query_parameters = self.query_parameters and True
  303. self.path_parameters = [
  304. p for p in self.parameters if p.is_type('path')]
  305. self.has_path_parameters = self.path_parameters and True
  306. self.header_parameters = [
  307. p for p in self.parameters if p.is_type('header')]
  308. self.has_header_parameters = self.header_parameters and True
  309. self.has_parameters = self.has_query_parameters or \
  310. self.has_path_parameters or self.has_header_parameters
  311. # Body param is different, since there's at most one
  312. self.body_parameter = [
  313. p for p in self.parameters if p.is_type('body')]
  314. if len(self.body_parameter) > 1:
  315. raise SwaggerError("Cannot have more than one body param", context)
  316. self.body_parameter = self.body_parameter and self.body_parameter[0]
  317. self.has_body_parameter = self.body_parameter and True
  318. self.summary = op_json.get('summary')
  319. self.notes = op_json.get('notes')
  320. err_json = op_json.get('errorResponses') or []
  321. self.error_responses = [
  322. ErrorResponse().load(j, processor, context) for j in err_json]
  323. self.has_error_responses = self.error_responses != []
  324. processor.process_operation(self, context)
  325. return self
  326. class Api(Stringify):
  327. """Model of a single API in an API declaration.
  328. See https://github.com/wordnik/swagger-core/wiki/API-Declaration
  329. """
  330. required_fields = ['path', 'operations']
  331. def __init__(self,):
  332. self.path = None
  333. self.description = None
  334. self.operations = []
  335. def load(self, api_json, processor, context):
  336. context = context.next_stack(api_json, 'path')
  337. validate_required_fields(api_json, self.required_fields, context)
  338. self.path = api_json.get('path')
  339. self.description = api_json.get('description')
  340. op_json = api_json.get('operations')
  341. self.operations = [
  342. Operation().load(j, processor, context) for j in op_json]
  343. self.has_websocket = \
  344. filter(lambda op: op.is_websocket, self.operations) != []
  345. processor.process_api(self, context)
  346. return self
  347. def get_list_parameter_type(type_string):
  348. """Returns the type parameter if the given type_string is List[].
  349. @param type_string: Type string to parse
  350. @returns Type parameter of the list, or None if not a List.
  351. """
  352. list_match = re.match('^List\[(.*)\]$', type_string)
  353. return list_match and list_match.group(1)
  354. class Property(Stringify):
  355. """Model of a Swagger property.
  356. See https://github.com/wordnik/swagger-core/wiki/datatypes
  357. """
  358. required_fields = ['type']
  359. def __init__(self, name):
  360. self.name = name
  361. self.type = None
  362. self.description = None
  363. self.required = None
  364. def load(self, property_json, processor, context):
  365. validate_required_fields(property_json, self.required_fields, context)
  366. # Bit of a hack, but properties do not self-identify
  367. context = context.next_stack({'name': self.name}, 'name')
  368. self.description = property_json.get('description') or ''
  369. self.required = property_json.get('required') or False
  370. type = property_json.get('type')
  371. self.type = type and SwaggerType().load(type, processor, context)
  372. processor.process_property(self, context)
  373. return self
  374. class Model(Stringify):
  375. """Model of a Swagger model.
  376. See https://github.com/wordnik/swagger-core/wiki/datatypes
  377. """
  378. required_fields = ['description', 'properties']
  379. def __init__(self):
  380. self.id = None
  381. self.subtypes = []
  382. self.__subtype_types = []
  383. self.notes = None
  384. self.description = None
  385. self.__properties = None
  386. self.__discriminator = None
  387. self.__extends_type = None
  388. def load(self, id, model_json, processor, context):
  389. context = context.next_stack(model_json, 'id')
  390. validate_required_fields(model_json, self.required_fields, context)
  391. # The duplication of the model's id is required by the Swagger spec.
  392. self.id = model_json.get('id')
  393. if id != self.id:
  394. raise SwaggerError("Model id doesn't match name", context)
  395. self.subtypes = model_json.get('subTypes') or []
  396. if self.subtypes and context.version_less_than("1.2"):
  397. raise SwaggerError("Type extension support added in Swagger 1.2",
  398. context)
  399. self.description = model_json.get('description')
  400. props = model_json.get('properties').items() or []
  401. self.__properties = [
  402. Property(k).load(j, processor, context) for (k, j) in props]
  403. self.__properties = sorted(self.__properties, key=lambda p: p.name)
  404. discriminator = model_json.get('discriminator')
  405. if discriminator:
  406. if context.version_less_than("1.2"):
  407. raise SwaggerError("Discriminator support added in Swagger 1.2",
  408. context)
  409. discr_props = [p for p in self.__properties if p.name == discriminator]
  410. if not discr_props:
  411. raise SwaggerError(
  412. "Discriminator '%s' does not name a property of '%s'" % (
  413. discriminator, self.id),
  414. context)
  415. self.__discriminator = discr_props[0]
  416. self.model_json = json.dumps(model_json,
  417. indent=2, separators=(',', ': '))
  418. processor.process_model(self, context)
  419. return self
  420. def extends(self):
  421. return self.__extends_type and self.__extends_type.id
  422. def set_extends_type(self, extends_type):
  423. self.__extends_type = extends_type
  424. def set_subtype_types(self, subtype_types):
  425. self.__subtype_types = subtype_types
  426. def discriminator(self):
  427. """Returns the discriminator, digging through base types if needed.
  428. """
  429. return self.__discriminator or \
  430. self.__extends_type and self.__extends_type.discriminator()
  431. def properties(self):
  432. base_props = []
  433. if self.__extends_type:
  434. base_props = self.__extends_type.properties()
  435. return base_props + self.__properties
  436. def has_properties(self):
  437. return len(self.properties()) > 0
  438. def all_subtypes(self):
  439. """Returns the full list of all subtypes, including sub-subtypes.
  440. """
  441. res = self.__subtype_types + \
  442. [subsubtypes for subtype in self.__subtype_types
  443. for subsubtypes in subtype.all_subtypes()]
  444. return sorted(res, key=lambda m: m.id)
  445. def has_subtypes(self):
  446. """Returns True if type has any subtypes.
  447. """
  448. return len(self.subtypes) > 0
  449. class ApiDeclaration(Stringify):
  450. """Model class for an API Declaration.
  451. See https://github.com/wordnik/swagger-core/wiki/API-Declaration
  452. """
  453. required_fields = [
  454. 'swaggerVersion', '_author', '_copyright', 'apiVersion', 'basePath',
  455. 'resourcePath', 'apis', 'models'
  456. ]
  457. def __init__(self):
  458. self.swagger_version = None
  459. self.author = None
  460. self.copyright = None
  461. self.api_version = None
  462. self.base_path = None
  463. self.resource_path = None
  464. self.apis = []
  465. self.models = []
  466. def load_file(self, api_declaration_file, processor):
  467. context = ParsingContext(None, [api_declaration_file])
  468. try:
  469. return self.__load_file(api_declaration_file, processor, context)
  470. except SwaggerError:
  471. raise
  472. except Exception as e:
  473. print >> sys.stderr, "Error: ", traceback.format_exc()
  474. raise SwaggerError(
  475. "Error loading %s" % api_declaration_file, context, e)
  476. def __load_file(self, api_declaration_file, processor, context):
  477. with open(api_declaration_file) as fp:
  478. self.load(json.load(fp), processor, context)
  479. expected_resource_path = '/api-docs/' + \
  480. os.path.basename(api_declaration_file) \
  481. .replace(".json", ".{format}")
  482. if self.resource_path != expected_resource_path:
  483. print >> sys.stderr, \
  484. "%s != %s" % (self.resource_path, expected_resource_path)
  485. raise SwaggerError("resourcePath has incorrect value", context)
  486. return self
  487. def load(self, api_decl_json, processor, context):
  488. """Loads a resource from a single Swagger resource.json file.
  489. """
  490. # If the version doesn't match, all bets are off.
  491. self.swagger_version = api_decl_json.get('swaggerVersion')
  492. context = context.next(version=self.swagger_version)
  493. if not self.swagger_version in SWAGGER_VERSIONS:
  494. raise SwaggerError(
  495. "Unsupported Swagger version %s" % self.swagger_version, context)
  496. validate_required_fields(api_decl_json, self.required_fields, context)
  497. self.author = api_decl_json.get('_author')
  498. self.copyright = api_decl_json.get('_copyright')
  499. self.api_version = api_decl_json.get('apiVersion')
  500. self.base_path = api_decl_json.get('basePath')
  501. self.resource_path = api_decl_json.get('resourcePath')
  502. api_json = api_decl_json.get('apis') or []
  503. self.apis = [
  504. Api().load(j, processor, context) for j in api_json]
  505. paths = set()
  506. for api in self.apis:
  507. if api.path in paths:
  508. raise SwaggerError("API with duplicated path: %s" % api.path, context)
  509. paths.add(api.path)
  510. self.has_websocket = filter(lambda api: api.has_websocket,
  511. self.apis) == []
  512. models = api_decl_json.get('models').items() or []
  513. self.models = [Model().load(id, json, processor, context)
  514. for (id, json) in models]
  515. self.models = sorted(self.models, key=lambda m: m.id)
  516. # Now link all base/extended types
  517. model_dict = dict((m.id, m) for m in self.models)
  518. for m in self.models:
  519. def link_subtype(name):
  520. res = model_dict.get(subtype)
  521. if not res:
  522. raise SwaggerError("%s has non-existing subtype %s",
  523. m.id, name)
  524. res.set_extends_type(m)
  525. return res;
  526. if m.subtypes:
  527. m.set_subtype_types([
  528. link_subtype(subtype) for subtype in m.subtypes])
  529. return self
  530. class ResourceApi(Stringify):
  531. """Model of an API listing in the resources.json file.
  532. """
  533. required_fields = ['path', 'description']
  534. def __init__(self):
  535. self.path = None
  536. self.description = None
  537. self.api_declaration = None
  538. def load(self, api_json, processor, context):
  539. context = context.next_stack(api_json, 'path')
  540. validate_required_fields(api_json, self.required_fields, context)
  541. self.path = api_json['path']
  542. self.description = api_json['description']
  543. if not self.path or self.path[0] != '/':
  544. raise SwaggerError("Path must start with /", context)
  545. processor.process_resource_api(self, context)
  546. return self
  547. def load_api_declaration(self, base_dir, processor):
  548. self.file = (base_dir + self.path).replace('{format}', 'json')
  549. self.api_declaration = ApiDeclaration().load_file(self.file, processor)
  550. processor.process_resource_api(self, [self.file])
  551. class ResourceListing(Stringify):
  552. """Model of Swagger's resources.json file.
  553. """
  554. required_fields = ['apiVersion', 'basePath', 'apis']
  555. def __init__(self):
  556. self.swagger_version = None
  557. self.api_version = None
  558. self.base_path = None
  559. self.apis = None
  560. def load_file(self, resource_file, processor):
  561. context = ParsingContext(None, [resource_file])
  562. try:
  563. return self.__load_file(resource_file, processor, context)
  564. except SwaggerError:
  565. raise
  566. except Exception as e:
  567. print >> sys.stderr, "Error: ", traceback.format_exc()
  568. raise SwaggerError(
  569. "Error loading %s" % resource_file, context, e)
  570. def __load_file(self, resource_file, processor, context):
  571. with open(resource_file) as fp:
  572. return self.load(json.load(fp), processor, context)
  573. def load(self, resources_json, processor, context):
  574. # If the version doesn't match, all bets are off.
  575. self.swagger_version = resources_json.get('swaggerVersion')
  576. if not self.swagger_version in SWAGGER_VERSIONS:
  577. raise SwaggerError(
  578. "Unsupported Swagger version %s" % swagger_version, context)
  579. validate_required_fields(resources_json, self.required_fields, context)
  580. self.api_version = resources_json['apiVersion']
  581. self.base_path = resources_json['basePath']
  582. apis_json = resources_json['apis']
  583. self.apis = [
  584. ResourceApi().load(j, processor, context) for j in apis_json]
  585. processor.process_resource_listing(self, context)
  586. return self
  587. def validate_required_fields(json, required_fields, context):
  588. """Checks a JSON object for a set of required fields.
  589. If any required field is missing, a SwaggerError is raised.
  590. @param json: JSON object to check.
  591. @param required_fields: List of required fields.
  592. @param context: Current context in the API.
  593. """
  594. missing_fields = [f for f in required_fields if not f in json]
  595. if missing_fields:
  596. raise SwaggerError(
  597. "Missing fields: %s" % ', '.join(missing_fields), context)