def test_resource(self): @resource(collection_path='/users', path='/users/{id}', name='user_service') class User(object): def __init__(self, request, context=None): self.request = request self.context = context def collection_get(self): return {'users': [1, 2, 3]} @view(renderer='json', content_type='application/json', schema=RequestSchema()) def collection_post(self): return {'test': 'yeah'} services = get_services() ret = _generate_swagger(services) self.assertEqual(sorted(ret["paths"].keys()), [ '/users', '/users/{id}', ]) self.assertEqual(sorted(ret["definitions"]['Body']["required"]), ['bar', 'foo'])
def get_swagger_json(http_scheme="http", http_host="localhost", base_url=None, use_docstring_summary=True): # type: (str, str, Optional[str], bool) -> JSON """Obtains the JSON schema of weaver API from request and response views schemas. :param http_scheme: Protocol scheme to use for building the API base if not provided by base URL parameter. :param http_host: Hostname to use for building the API base if not provided by base URL parameter. :param base_url: Explicit base URL to employ of as API base instead of HTTP scheme/host parameters. :param use_docstring_summary: Setting that controls if function docstring should be used to auto-generate the summary field of responses. .. seealso:: - :mod:`weaver.wps_restapi.swagger_definitions` """ CorniceSwagger.type_converter = CustomTypeConversionDispatcher swagger = CorniceSwagger(get_services()) # function docstrings are used to create the route's summary in Swagger-UI swagger.summary_docstrings = use_docstring_summary swagger_base_spec = {"schemes": [http_scheme]} if base_url: weaver_parsed_url = urlparse(base_url) swagger_base_spec["host"] = weaver_parsed_url.netloc swagger_base_path = weaver_parsed_url.path else: swagger_base_spec["host"] = http_host swagger_base_path = sd.api_frontpage_uri swagger.swagger = swagger_base_spec return swagger.generate(title=sd.API_TITLE, version=weaver_version, base_path=swagger_base_path)
def run(self): # clear the SERVICES variable, which will allow to use this # directive multiple times clear_services() app_name = self.options.get('app') if app_name: app = import_module(app_name) app.main({}) # import the modules, which will populate the SERVICES variable. for module in self.options.get('modules', []): if module in MODULES: reload(MODULES[module]) else: MODULES[module] = import_module(module) names = self.options.get('services', []) service = self.options.get('service') if service is not None: names.append(service) # filter the services according to the options we got services = get_services(names=names or None, exclude=self.options.get('exclude')) return [self._render_service(s) for s in services]
def openAPI_v1_spec(request): services = get_services() services.sort(key=attrgetter('path')) CorniceSwagger.schema_transformers.append(body_schema_transformer) CorniceSwagger.type_converter = TypeConverterWithDeferredSupport CorniceSwagger.type_converter.deferred_args = { 'repository': request.repository } doc = CorniceSwagger(services) extra_fields = { 'securityDefinitions': { 'jwt': { 'type': 'apiKey', 'description': ('Enter a valid token as returned by the ' '/auth/login endpoint.\n\n' 'Note: The token should be prefixed with "Bearer "'), 'in': 'header', 'name': 'Authorization' } } } my_spec = doc.generate('Idris API', '1.0.0', swagger=extra_fields) return my_spec
def openapi_view(request): # Only build json once try: return openapi_view.__json__ except AttributeError: openapi_view.__json__ = OpenAPI(get_services(), request).generate() return openapi_view.__json__
def scan_api(root=None): from cornice.service import get_services for service in get_services(): for method, func, options in service.definitions: wsme_func = getattr(func, 'wsme_func') basepath = service.path.split('/') if basepath and not basepath[0]: del basepath[0] if wsme_func: yield (basepath + [method.lower()], wsme_func._wsme_definition)
def scan_api(root=None): from cornice.service import get_services for service in get_services(): for method, func, options in service.definitions: wsme_func = getattr(func, 'wsme_func') basepath = service.path.split('/') if basepath and not basepath[0]: del basepath[0] if wsme_func: yield ( basepath + [method.lower()], wsme_func._wsme_definition )
def test_generate_spore_description(self): coffees = Service(name='Coffees', path='/coffee') coffee = Service(name='coffee', path='/coffee/{bar}/{id}') @coffees.post() def post_coffees(request): """Post information about the coffee""" return "ok" self._define_coffee_methods(coffee) self._define_coffee_methods(coffees) services = get_services(names=('coffee', 'Coffees')) spore = generate_spore_description(services, name="oh yeah", base_url="http://localhost/", version="1.0") # basic fields self.assertEqual(spore['name'], "oh yeah") self.assertEqual(spore['base_url'], "http://localhost/") self.assertEqual(spore['version'], "1.0") # methods methods = spore['methods'] self.assertIn('get_coffees', methods) self.assertDictEqual(methods['get_coffees'], { 'path': '/coffee', 'method': 'GET', 'formats': ['json'], }) self.assertIn('post_coffees', methods) self.assertDictEqual( methods['post_coffees'], { 'path': '/coffee', 'method': 'POST', 'formats': ['json'], 'description': post_coffees.__doc__ }) self.assertIn('get_coffee', methods) self.assertDictEqual( methods['get_coffee'], { 'path': '/coffee/:bar/:id', 'method': 'GET', 'formats': ['json'], 'required_params': ['bar', 'id'] })
def run(self): # import the modules, which will populate the SERVICES variable. for module in self.options.get("modules"): import_module(module) names = self.options.get("services", []) service = self.options.get("service") if service is not None: names.append(service) # filter the services according to the options we got services = get_services(names=names or None, exclude=self.options.get("exclude")) return [self._render_service(s) for s in services]
def run(self): # import the modules, which will populate the SERVICES variable. for module in self.options.get('modules'): import_module(module) names = self.options.get('services', []) service = self.options.get('service') if service is not None: names.append(service) # filter the services according to the options we got services = get_services(names=names or None, exclude=self.options.get('exclude')) return [self._render_service(s) for s in services]
def test_generate_spore_description(self): coffees = Service(name='Coffees', path='/coffee') coffee = Service(name='coffee', path='/coffee/{bar}/{id}') @coffees.post() def post_coffees(request): """Post information about the coffee""" return "ok" self._define_coffee_methods(coffee) self._define_coffee_methods(coffees) services = get_services(names=('coffee', 'Coffees')) spore = generate_spore_description( services, name="oh yeah", base_url="http://localhost/", version="1.0") # basic fields self.assertEqual(spore['name'], "oh yeah") self.assertEqual(spore['base_url'], "http://localhost/") self.assertEqual(spore['version'], "1.0") # methods methods = spore['methods'] self.assertIn('get_coffees', methods) self.assertDictEqual(methods['get_coffees'], { 'path': '/coffee', 'method': 'GET', 'formats': ['json'], }) self.assertIn('post_coffees', methods) self.assertDictEqual(methods['post_coffees'], { 'path': '/coffee', 'method': 'POST', 'formats': ['json'], 'description': post_coffees.__doc__ }) self.assertIn('get_coffee', methods) self.assertDictEqual(methods['get_coffee'], { 'path': '/coffee/:bar/:id', 'method': 'GET', 'formats': ['json'], 'required_params': ['bar', 'id'] })
def test_get_services(self): self.assertEqual([], get_services()) foobar = Service("Foobar", "/foobar") self.assertIn(foobar, get_services()) barbaz = Service("Barbaz", "/barbaz") self.assertIn(barbaz, get_services()) self.assertEqual([barbaz], get_services(exclude=["Foobar"])) self.assertEqual([foobar], get_services(names=["Foobar"])) self.assertEqual([foobar, barbaz], get_services(names=["Foobar", "Barbaz"]))
def test_get_services(self): self.assertEqual([], get_services()) foobar = Service("Foobar", "/foobar") self.assertIn(foobar, get_services()) barbaz = Service("Barbaz", "/barbaz") self.assertIn(barbaz, get_services()) self.assertEqual([barbaz, ], get_services(exclude=['Foobar', ])) self.assertEqual([foobar, ], get_services(names=['Foobar', ])) self.assertEqual([foobar, barbaz], get_services(names=['Foobar', 'Barbaz']))
def test_rxjson_spore(self): rx = Rx.Factory({'register_core_types': True}) coffees = Service(name='Coffees', path='/coffee') coffee = Service(name='coffee', path='/coffee/{bar}/{id}') self._define_coffee_methods(coffee) self._define_coffee_methods(coffees) services = get_services(names=('coffee', 'Coffees')) spore = generate_spore_description( services, name="oh yeah", base_url="http://localhost/", version="1.0") with open(os.path.join(HERE, 'spore_validation.rx')) as f: spore_json_schema = json.loads(f.read()) spore_schema = rx.make_schema(spore_json_schema) self.assertTrue(spore_schema.check(spore))
def generate_api_schema(swagger_base_spec): # type: (Dict[str, Union[str, List[str]]]) -> JSON """ Return JSON Swagger specifications of Cowbird REST API. Uses Cornice Services and Schemas to return swagger specification. :param swagger_base_spec: dictionary that specifies the 'host' and list of HTTP 'schemes' to employ. """ generator = CorniceSwagger(get_services()) # function docstrings are used to create the route's summary in Swagger-UI generator.summary_docstrings = True generator.default_security = get_security swagger_base_spec.update(SecurityDefinitionsAPI) generator.swagger = swagger_base_spec json_api_spec = generator.generate(title=TitleAPI, version=__meta__.__version__, info=InfoAPI) for tag in json_api_spec["tags"]: tag["description"] = TAG_DESCRIPTIONS[tag["name"]] return json_api_spec
def openapi_specification(request): # pylint: disable=unused-argument """OpenAPI specification""" doc = CorniceSwagger(get_services()) doc.summary_docstrings = True return doc.generate('PyAMS', '1.0')
def openAPI_spec(request): my_generator = CorniceSwagger(services=get_services()) my_generator.summary_docstrings = True return my_generator.generate('Catalog Manager', '1.0.0')
def get_spore(request): services = get_services() return generate_spore_description(services, 'OpenRegistry', request.application_url, VERSION)
def get_spore(request): services = get_services() return generate_spore_description(services, "Service name", request.application_url, VERSION)
def openAPI_spec(request): doc = CorniceSwagger(get_services()) doc.summary_docstrings = True my_spec = doc.generate('MyAPI', '1.0.0') return my_spec
def openAPI_spec(request): my_generator = CorniceSwagger(get_services()) my_spec = my_generator("MyAPI", "1.0.0") return my_spec
def get_openapi_json(http_scheme="http", http_host="localhost", base_url=None, use_refs=True, use_docstring_summary=True, settings=None): # type: (str, str, Optional[str], bool, bool, Optional[SettingsType]) -> JSON """ Obtains the JSON schema of Weaver OpenAPI from request and response views schemas. :param http_scheme: Protocol scheme to use for building the API base if not provided by base URL parameter. :param http_host: Hostname to use for building the API base if not provided by base URL parameter. :param base_url: Explicit base URL to employ of as API base instead of HTTP scheme/host parameters. :param use_refs: Generate schemas with ``$ref`` definitions or expand every schema content. :param use_docstring_summary: Extra function docstring to auto-generate the summary field of responses. :param settings: Application settings to retrieve further metadata details to be added to the OpenAPI. .. seealso:: - :mod:`weaver.wps_restapi.swagger_definitions` """ CorniceSwagger.type_converter = OAS3TypeConversionDispatcher depth = -1 if use_refs else 0 swagger = CorniceSwagger(get_services(), def_ref_depth=depth, param_ref=use_refs, resp_ref=use_refs) # function docstrings are used to create the route's summary in Swagger-UI swagger.summary_docstrings = use_docstring_summary swagger_base_spec = {"schemes": [http_scheme]} if base_url: weaver_parsed_url = urlparse(base_url) swagger_base_spec["host"] = weaver_parsed_url.netloc swagger_base_path = weaver_parsed_url.path else: swagger_base_spec["host"] = http_host swagger_base_path = sd.api_frontpage_service.path swagger.swagger = swagger_base_spec swagger_info = { "description": __meta__.__description__, "licence": { "name": __meta__.__license_type__, "url": "{}/blob/master/LICENSE.txt".format( __meta__.__source_repository__), } } if settings: for key in ["name", "email", "url"]: val = settings.get("weaver.wps_metadata_contact_{}".format(key)) if val: swagger_info.setdefault("contact", {}) swagger_info["contact"][key] = val abstract = settings.get("weaver.wps_metadata_identification_abstract") if abstract: swagger_info["description"] = "{}\n\n{}".format( abstract, __meta__.__description__) terms = settings.get( "weaver.wps_metadata_identification_accessconstraints") if terms and "http" in terms: if "," in terms: terms = [term.strip() for term in terms.split(",")] else: terms = [terms] terms = [term for term in terms if "http" in term] if terms: swagger_info["termsOfService"] = terms[0] swagger_json = swagger.generate(title=sd.API_TITLE, version=__meta__.__version__, info=swagger_info, base_path=swagger_base_path, openapi_spec=3) swagger_json["externalDocs"] = sd.API_DOCS return swagger_json
def generate_json(request): # pragma: no cover serv_json = CorniceSwagger(get_services()) spec = serv_json.generate('Senic Hub API', request.registry.settings.get('hub_api_version')) return spec
def get_spore(request): services = get_services() return generate_spore_description(services, 'Service name', request.application_url, request.registry.settings.get('api_version', VERSION))
def open_api_spec(request): doc = CorniceSwagger(get_services()) my_spec = doc.generate('IMIO Internal REST API', '1.0.0') return my_spec
def openAPI_spec(request): doc = CorniceSwagger(get_services()) my_spec = doc.generate('MyAPI', '1.0.0') return my_spec
def get_spore(request): return generate_spore_description(get_services(), 'daybed', request.application_url, VERSION)
def setUp(self): super(OpenAPITest, self).setUp() self.request = mock.MagicMock() self.request.registry.settings = self.get_app_settings() self.generator = OpenAPI(get_services(), self.request) self.api_doc = self.generator.generate()
def openAPI_spec(request): doc = CorniceSwagger(get_services()) my_spec = doc.generate('Kedja API', '1.0.0', swagger={'host': request.host}) return my_spec
def get_spore(request): services = get_services() return generate_spore_description( services, 'Service name', request.application_url, request.registry.settings.get('api_version', VERSION))
def get_services_(): return [ service for service in get_services() if service.name in AVAILABLE_SERVICES ]
def get_spore(request): services = get_services() return generate_spore_description(services, 'Service name', request.application_url, VERSION)
def get_spore(request): services = get_services() return generate_spore_description(services, 'Service name', request.application_url, request.registry.api_version)
def openAPI_spec(request): doc = CorniceSwagger(get_services()) doc.summary_docstrings = True return doc.generate("Kernel", "0.1")