def run_server(): app = App(__name__) print("Connexion app created") # Set configurations for connexion app app.host = '0.0.0.0' app.port = '8080' app.debug = True print("connexion app configured") # Register MongoDB app.app.config["MONGO_URI"] = "mongodb://localhost:27017/PG3" # TODO: Try to remove this datebase name later mongo = PyMongo(app.app) # db = mongo.db['PG1'] resident = { "Room": "102", "Name": "Sarthak Gupta", "Hometown": "Jammu", "Company": "Intuit" } collection1id = mongo.db['collection1'].insert_one(resident).inserted_id print("Database should be created till now") app.add_api('swagger.yaml') return app
def build_app(apis, host=_host, port=_port, server=_server, ui=_ui): app = App(__name__, host=host, port=port, server=server, swagger_ui=ui) for api in apis: app.add_api(api) return app
def get_app(): app = App(__name__, specification_dir="./openapi/") app.app.json_encoder = JSONEncoder app.add_api("openapi.yaml", arguments={"title": "Ibutsu"}, base_path="/api", pythonic_params=True) CORS(app.app) FlaskDynaconf(app.app) @app.route("/") def index(): return redirect("/api/ui/", code=302) @app.route("/admin/run-task", methods=["POST"]) def run_task(): params = request.get_json(force=True, silent=True) if not params: return "Bad request", 400 task_path = params.get("task") task_params = params.get("params", {}) if not task_path: return "Bad request", 400 task_module, task_name = task_path.split(".", 2) try: mod = import_module(f"ibutsu_server.tasks.{task_module}") except ImportError: return "Not found", 404 if not hasattr(mod, task_name): return "Not found", 404 task = getattr(mod, task_name) task.delay(**task_params) return "Accepted", 202 return app
def app(): cnx_app = App(__name__, port=5001, specification_dir=SPEC_FOLDER, debug=True) cnx_app.add_api('api.yaml', validate_responses=True) return cnx_app
def test_handle_add_operation_error(simple_api_spec_dir): app = App(__name__, specification_dir=simple_api_spec_dir) app.api_cls = type('AppTest', (app.api_cls, ), {}) app.api_cls.add_operation = mock.MagicMock( side_effect=Exception('operation error!')) with pytest.raises(Exception): app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
def test_validator_map(json_validation_spec_dir, spec): def validate_type(validator, types, instance, schema): types = _utils.ensure_list(types) errors = Draft4RequestValidator.VALIDATORS['type'](validator, types, instance, schema) yield from errors if 'string' in types and 'minLength' not in schema: errors = Draft4RequestValidator.VALIDATORS['minLength'](validator, 1, instance, schema) yield from errors MinLengthRequestValidator = extend(Draft4RequestValidator, {'type': validate_type}) class MyRequestBodyValidator(RequestBodyValidator): def __init__(self, *args, **kwargs): super().__init__(*args, validator=MinLengthRequestValidator, **kwargs) validator_map = {'body': MyRequestBodyValidator} app = App(__name__, specification_dir=json_validation_spec_dir) app.add_api(spec, validate_responses=True, validator_map=validator_map) app_client = app.app.test_client() res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': 'bar'}), content_type='application/json') # type: flask.Response assert res.status_code == 200 res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': ''}), content_type='application/json') # type: flask.Response assert res.status_code == 400
def test_validator_map(json_validation_spec_dir, spec): def validate_type(validator, types, instance, schema): types = _utils.ensure_list(types) errors = Draft4RequestValidator.VALIDATORS['type'](validator, types, instance, schema) for e in errors: yield e if 'string' in types and 'minLength' not in schema: errors = Draft4RequestValidator.VALIDATORS['minLength'](validator, 1, instance, schema) for e in errors: yield e MinLengthRequestValidator = extend(Draft4RequestValidator, {'type': validate_type}) class MyRequestBodyValidator(RequestBodyValidator): def __init__(self, *args, **kwargs): super(MyRequestBodyValidator, self).__init__(*args, validator=MinLengthRequestValidator, **kwargs) validator_map = {'body': MyRequestBodyValidator} app = App(__name__, specification_dir=json_validation_spec_dir) app.add_api(spec, validate_responses=True, validator_map=validator_map) app_client = app.app.test_client() res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': 'bar'}), content_type='application/json') # type: flask.Response assert res.status_code == 200 res = app_client.post('/v1.0/minlength', data=json.dumps({'foo': ''}), content_type='application/json') # type: flask.Response assert res.status_code == 400
def test_swagger_json_api(simple_api_spec_dir): """ Verify the swagger.json file is returned for default setting passed to api. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api('swagger.yaml') app_client = app.app.test_client() swagger_json = app_client.get('/v1.0/swagger.json') # type: flask.Response assert swagger_json.status_code == 200
def create_app(): connexion_app = App( 'demo', specification_dir='swagger/', options={"swagger_ui": False} ) connexion_app.add_api( 'api.spec.yaml', validate_responses=True, strict_validation=True ) return connexion_app
def test_no_swagger_json_api(simple_api_spec_dir): """ Verify the swagger.json file is not returned when set to False when adding api. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api('swagger.yaml', swagger_json=False) app_client = app.app.test_client() swagger_json = app_client.get('/v1.0/swagger.json') # type: flask.Response assert swagger_json.status_code == 404
def test_no_swagger_json_api(simple_api_spec_dir, spec): """ Verify the spec json file is not returned when set to False when adding api. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(spec, options={"serve_spec": False}) app_client = app.app.test_client() url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json")) swagger_json = app_client.get(url) # type: flask.Response assert swagger_json.status_code == 404
def test_swagger_json_app(simple_api_spec_dir, spec): """ Verify the spec json file is returned for default setting passed to app. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(spec) app_client = app.app.test_client() url = '/v1.0/{spec}' url = url.format(spec=spec.replace("yaml", "json")) spec_json = app_client.get(url) # type: flask.Response assert spec_json.status_code == 200
def test_app_with_relative_path(simple_api_spec_dir): # Create the app with a relative path and run the test_app testcase below. app = App(__name__, port=5001, specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER), debug=True) app.add_api('swagger.yaml') app_client = app.app.test_client() get_bye = app_client.get('/v1.0/bye/jsantos') # type: flask.Response assert get_bye.status_code == 200 assert get_bye.data == b'Goodbye jsantos'
def test_app_with_relative_path(simple_api_spec_dir, spec): # Create the app with a relative path and run the test_app testcase below. app = App(__name__, port=5001, specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER), debug=True) app.add_api(spec) app_client = app.app.test_client() get_bye = app_client.get('/v1.0/bye/jsantos') # type: flask.Response assert get_bye.status_code == 200 assert get_bye.data == b'Goodbye jsantos'
def test_no_swagger_ui_config_json(simple_api_spec_dir, spec): """ Verify the swagger-ui-config.json file is not returned when the swagger_ui_config option not passed to app. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(spec) app_client = app.app.test_client() url = '/v1.0/ui/swagger-ui-config.json' swagger_ui_config_json = app_client.get(url) # type: flask.Response assert swagger_ui_config_json.status_code == 404
def build_app(apis, host=_host, port=_port, ui=_ui): app = App(__name__, host=host, port=port, server='flask', options={'swagger_ui': ui}) for api in apis: app.add_api(api) app.app.config['APPINSIGHTS_INSTRUMENTATIONKEY'] = config.APPINSIGHTS_KEY app.app.config['APPINSIGHTS_ENDPOINT_URI'] = config.APPINSIGHTS_HOST app.app.config['APPINSIGHTS_DISABLE_TRACE_LOGGING'] = True AppInsights(app.app) return app
def test_swagger_json_api(simple_api_spec_dir, spec): """ Verify the spec json file is returned for default setting passed to api. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(spec) app_client = app.app.test_client() url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json")) swagger_json = app_client.get(url) # type: flask.Response assert swagger_json.status_code == 200
def create_app(): connexion_app = App( 'demo', specification_dir='swagger/', options={"swagger_ui": False} ) connexion_app.add_api( 'api.spec.yaml', validate_responses=True, strict_validation=True ) prometheus_app = make_wsgi_app() dispatcher = DispatcherMiddleware(connexion_app, {"/metrics": prometheus_app}) return dispatcher
def test_swagger_yaml_app(simple_api_spec_dir, spec): """ Verify the spec yaml file is returned for default setting passed to app. """ app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(spec) app_client = app.app.test_client() url = '/v1.0/{spec}' url = url.format(spec=spec) spec_response = app_client.get(url) # type: flask.Response assert spec_response.status_code == 200
def build_app_from_fixture(api_spec_folder, **kwargs): debug = True if 'debug' in kwargs: debug = kwargs['debug'] del (kwargs['debug']) cnx_app = App(__name__, port=5001, specification_dir=FIXTURES_FOLDER / api_spec_folder, debug=debug) cnx_app.add_api('swagger.yaml', **kwargs) return cnx_app
def activate(self, callback=None, app=None, twisted=False): self.setup() if self.swagger.has_api: swagger_file = '{}/{}'.format(self.swagger.path, self.swagger.file) if not Path(swagger_file).is_file(): self.logger.info( 'Unable to access swagger file "{}"'.format(swagger_file)) return swagger_ui = self.get('swagger_ui', 'ui') app = App(__name__, specification_dir='{}/{}'.format(getcwd(), self.swagger.path)) app.add_api(self.swagger.file, arguments={'title': self.ms_name}, swagger_url=swagger_ui) self.swagger.add_healthcheck(app) CORS(app.app) @app.app.teardown_appcontext def flush_session_manager(_): self.db.session.remove() else: if not app: app = Flask(__name__) CORS(app) @app.teardown_appcontext def flush_session_manager(_): self.db.session.remove() reactor.suggestThreadPoolSize(200) client._HTTP11ClientFactory.noisy = False if callback: callback(app) # Sorry, flask_private is the only remotely sane way I can think of doing # this at the moment. It's a special case for endpoints in the API gateway. if self.get('flask_private', False, boolean=True): port = self.get('flask_port') else: port = self.flask_port self.logger.info('* starting listening port "{}"'.format(port)) if twisted: self.logger.info('* starting Twisted WSGI server') Twisted(app).run(host='0.0.0.0', port=port, debug=False) else: self.logger.info('* starting Flask dev server') app.run(host='0.0.0.0', port=port, debug=False)
def register_openapi( app: App, specs: List[Dict] = [], add_security_definitions: bool = True ) -> App: """Registers OpenAPI specs with Connexion app.""" # Iterate over list of API specs for spec in specs: # Get _this_ directory path = os.path.join( os.path.abspath( os.path.dirname( os.path.realpath(__file__) ) ), get_conf(spec, 'path') ) # Add security definitions to copy of specs if add_security_definitions: path = __add_security_definitions(in_file=path) # Generate API endpoints from OpenAPI spec try: app.add_api( path, strict_validation=get_conf(spec, 'strict_validation'), validate_responses=get_conf(spec, 'validate_responses'), swagger_ui=get_conf(spec, 'swagger_ui'), swagger_json=get_conf(spec, 'swagger_json'), ) logger.info("API endpoints specified in '{path}' added.".format( path=path, )) except (FileNotFoundError, PermissionError) as e: logger.critical( ( "API specification file not found or accessible at " "'{path}'. Execution aborted. Original error message: " "{type}: {msg}" ).format( path=path, type=type(e).__name__, msg=e, ) ) raise SystemExit(1) return(app)
def build_app(apis, host=_host, port=_port, ui=_ui): app = App(__name__, host=host, port=port, server='flask', options={'swagger_ui': ui}) for api in apis: app.add_api(api) _configure_flask(app.app) return app
def build_app_inject_from_fixture(api_spec_folder, **kwargs): debug = True if 'debug' in kwargs: debug = kwargs['debug'] del (kwargs['debug']) cnx_app = App(__name__, port=5001, specification_dir=FIXTURES_FOLDER / api_spec_folder, debug=debug) cnx_app.add_api('swagger.yaml', resolver=RestyResolver('api'), **kwargs) FlaskInjector(app=cnx_app.app, modules=[configure]) return cnx_app
def test_swagger_ui_with_config(simple_api_spec_dir, spec): swagger_ui_config = {"displayOperationId": True} options = {"swagger_ui_config": swagger_ui_config} app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, options=options, debug=True) app.add_api(spec) app_client = app.app.test_client() swagger_ui = app_client.get('/v1.0/ui/') # type: flask.Response assert swagger_ui.status_code == 200 if "openapi" in spec: assert b'configUrl: "swagger-ui-config.json"' in swagger_ui.data
def test_using_all_fields_in_path_item(simple_api_spec_dir): """Test that connexion will try to add an endpoint only on http methods. test also that each http methods has its own endpoint. """ app = App(__name__, specification_dir=simple_api_spec_dir) app.add_api('openapi.yaml') test_methods = set() for rule in app.app.url_map.iter_rules(): if rule.rule != "/v1.0/add_operation_on_http_methods_only": continue test_methods.update({method.lower() for method in rule.methods}) assert set(test_methods) == METHODS
def test_no_swagger_ui(simple_api_spec_dir): app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, swagger_ui=False, debug=True) app.add_api('swagger.yaml') app_client = app.app.test_client() swagger_ui = app_client.get('/v1.0/ui/') # type: flask.Response assert swagger_ui.status_code == 404 app2 = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app2.add_api('swagger.yaml', swagger_ui=False) app2_client = app2.app.test_client() swagger_ui2 = app2_client.get('/v1.0/ui/') # type: flask.Response assert swagger_ui2.status_code == 404
def test_swagger_ui(simple_api_spec_dir, spec): app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(spec) app_client = app.app.test_client() swagger_ui = app_client.get('/v1.0/ui/') # type: flask.Response assert swagger_ui.status_code == 200 spec_json_filename = '/v1.0/{spec}'.format( spec=spec.replace("yaml", "json")) assert spec_json_filename.encode() in swagger_ui.data if "openapi" in spec: assert b'swagger-ui-config.json' not in swagger_ui.data
def test_app_with_different_uri_parser(simple_api_spec_dir): from connexion.decorators.uri_parsing import FirstValueURIParser app = App(__name__, port=5001, specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER), options={"uri_parser_class": FirstValueURIParser}, debug=True) app.add_api('swagger.yaml') app_client = app.app.test_client() resp = app_client.get( '/v1.0/test_array_csv_query_param?items=a,b,c&items=d,e,f' ) # type: flask.Response assert resp.status_code == 200 j = json.loads(resp.get_data(as_text=True)) assert j == ['a', 'b', 'c']
def create_app() -> App: """:return: lazily created and initialized app""" new_app = App(__name__, specification_dir='swagger') setup_app(new_app.app) from ..flask_modules.connexion import TaggedSimpleResolver from . import controller new_app.add_api('api.yaml', validate_responses=True, resolver=TaggedSimpleResolver(controller), swagger_url='/api') new_app.add_url_rule('/', 'health', lambda: 'ok') return new_app
def test_no_swagger_ui(simple_api_spec_dir, spec): options = {"swagger_ui": False} app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, options=options, debug=True) app.add_api(spec) app_client = app.app.test_client() swagger_ui = app_client.get('/v1.0/ui/') # type: flask.Response assert swagger_ui.status_code == 404 app2 = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app2.add_api(spec, options={"swagger_ui": False}) app2_client = app2.app.test_client() swagger_ui2 = app2_client.get('/v1.0/ui/') # type: flask.Response assert swagger_ui2.status_code == 404
def test_swagger_ui_config_json(simple_api_spec_dir, spec): """ Verify the swagger-ui-config.json file is returned for swagger_ui_config option passed to app. """ swagger_ui_config = {"displayOperationId": True} options = {"swagger_ui_config": swagger_ui_config} app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, options=options, debug=True) app.add_api(spec) app_client = app.app.test_client() url = '/v1.0/ui/swagger-ui-config.json' swagger_ui_config_json = app_client.get(url) # type: flask.Response assert swagger_ui_config_json.status_code == 200 assert swagger_ui_config == json.loads( swagger_ui_config_json.get_data(as_text=True))
def init_api_connexion(app: Flask) -> None: """Initialize Stable API""" base_path = '/api/v1' from airflow.www import views @app.errorhandler(404) @app.errorhandler(405) def _handle_api_error(ex): if request.path.startswith(base_path): # 404 errors are never handled on the blueprint level # unless raised from a view func so actual 404 errors, # i.e. "no route for it" defined, need to be handled # here on the application level return common_error_handler(ex) else: return views.not_found(ex) spec_dir = path.join(ROOT_APP_DIR, 'api_connexion', 'openapi') connexion_app = App(__name__, specification_dir=spec_dir, skip_error_handlers=True) connexion_app.app = app api_bp = connexion_app.add_api(specification='v1.yaml', base_path=base_path, validate_responses=True, strict_validation=True).blueprint # Like "api_bp.after_request", but the BP is already registered, so we have # to register it in the app directly. app.after_request_funcs.setdefault(api_bp.name, []).append(set_cors_headers_on_response) app.register_error_handler(ProblemException, common_error_handler) app.extensions['csrf'].exempt(api_bp)
def test_handle_add_operation_error_debug(simple_api_spec_dir): app = App(__name__, specification_dir=simple_api_spec_dir, debug=True) app.api_cls = type('AppTest', (app.api_cls,), {}) app.api_cls.add_operation = mock.MagicMock(side_effect=Exception('operation error!')) api = app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar')) assert app.api_cls.add_operation.called assert api.resolver.resolve_function_from_operation_id('faux')('bah') == 'bar'
def test_app_with_different_uri_parser(simple_api_spec_dir): from connexion.decorators.uri_parsing import Swagger2URIParser app = App(__name__, port=5001, specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER), options={"uri_parser_class": Swagger2URIParser}, debug=True) app.add_api('swagger.yaml') app_client = app.app.test_client() resp = app_client.get( '/v1.0/test_array_csv_query_param?items=a,b,c&items=d,e,f' ) # type: flask.Response assert resp.status_code == 200 j = json.loads(resp.get_data(as_text=True)) assert j == ['d', 'e', 'f']
def _build_app(model_dir, cors): '''Builds and returns a Flask app''' connexion_app = App(__name__, specification_dir=model_dir) connexion_app.add_api('oas.yaml', resolver=_CustomResolver()) flask_app = connexion_app.app flask_app.model = load_model(model_dir) flask_app.model_dir = model_dir flask_app.methods_info = _read_methods(model_dir) @flask_app.route('/') def redirect_ui(): return redirect('/ui') _apply_cors(flask_app, cors) return flask_app
def test_app_with_resolver(simple_api_spec_dir, spec): from connexion.resolver import Resolver resolver = Resolver() app = App(__name__, port=5001, specification_dir='..' / simple_api_spec_dir.relative_to(TEST_FOLDER), resolver=resolver) api = app.add_api(spec) assert api.resolver is resolver
def test_dict_as_yaml_path(simple_api_spec_dir): swagger_yaml_path = simple_api_spec_dir / 'swagger.yaml' with swagger_yaml_path.open(mode='rb') as swagger_yaml: contents = swagger_yaml.read() try: swagger_template = contents.decode() except UnicodeDecodeError: swagger_template = contents.decode('utf-8', 'replace') swagger_string = jinja2.Template(swagger_template).render({}) specification = yaml.safe_load(swagger_string) # type: dict app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(specification) app_client = app.app.test_client() swagger_json = app_client.get('/v1.0/swagger.json') # type: flask.Response assert swagger_json.status_code == 200
def test_dict_as_yaml_path(simple_api_spec_dir, spec): openapi_yaml_path = simple_api_spec_dir / spec with openapi_yaml_path.open(mode='rb') as openapi_yaml: contents = openapi_yaml.read() try: openapi_template = contents.decode() except UnicodeDecodeError: openapi_template = contents.decode('utf-8', 'replace') openapi_string = jinja2.Template(openapi_template).render({}) specification = yaml.load(openapi_string, ExtendedSafeLoader) # type: dict app = App(__name__, port=5001, specification_dir=simple_api_spec_dir, debug=True) app.add_api(specification) app_client = app.app.test_client() url = '/v1.0/{spec}'.format(spec=spec.replace("yaml", "json")) swagger_json = app_client.get(url) # type: flask.Response assert swagger_json.status_code == 200
from connexion import App import logging logging.basicConfig(level=logging.INFO) app = App(__name__) app.add_api('swagger.yaml') # set the WSGI application callable to allow using uWSGI application = app.app if __name__ == '__main__': app.run(port=8080, server='gevent')
def test_handle_add_operation_error(simple_api_spec_dir): app = App(__name__, specification_dir=simple_api_spec_dir) app.api_cls = type('AppTest', (app.api_cls,), {}) app.api_cls.add_operation = mock.MagicMock(side_effect=Exception('operation error!')) with pytest.raises(Exception): app.add_api('swagger.yaml', resolver=lambda oid: (lambda foo: 'bar'))
def test_add_api_with_function_resolver_function_is_wrapped(simple_api_spec_dir, spec): app = App(__name__, specification_dir=simple_api_spec_dir) api = app.add_api(spec, resolver=lambda oid: (lambda foo: 'bar')) assert api.resolver.resolve_function_from_operation_id('faux')('bah') == 'bar'