def spec(request): return APISpec( title='Swagger Petstore', version='1.0.0', openapi_version=request.param, plugins=(FlaskPlugin(), ), )
def generate_swagger() -> str: # Create an APISpec spec = APISpec( title="ARCOR2 Data Models", version=arcor2.api_version(), openapi_version="3.0.2", plugins=[FlaskPlugin(), DataclassesPlugin()], ) # TODO avoid explicit naming of all sub-modules in rpc module for module in (arcor2.data.common, arcor2.data.object_type, rpc.common, rpc.execution, rpc.objects, rpc.robot, rpc.scene, rpc.project, rpc.services, rpc.storage, arcor2.data.events): for name, obj in inspect.getmembers(module): if not inspect.isclass(obj) or not issubclass( obj, JsonSchemaMixin) or obj == JsonSchemaMixin: continue try: spec.components.schema(obj.__name__, schema=obj) except DuplicateComponentNameError: continue return spec.to_yaml()
def register_spec(test=False, test_host="localhost", test_port=12345): servers = ([{ "url": f"http://{test_host}:{test_port}", "description": "Test server" }] if test else []) # Create an APISpec spec = APISpec( title="OpenReferee", version=__version__, openapi_version="3.0.2", info={ "contact": { "name": "Indico Team", "url": "https://github.com/indico/openreferee", "email": "*****@*****.**", } }, plugins=[FlaskPlugin(), MarshmallowPlugin()], servers=servers, tags=[{ "name": t } for t in ("create", "event", "get", "info", "remove", "service")], ) spec.components.security_scheme("bearer_token", { "type": "http", "scheme": "bearer" }) return spec
def create_app(): app = Flask(__name__) app.config.from_object("backend.config.cfg") register_extensions(app) # register blueprints app.register_blueprint(player_blueprint) # define swagger spec = APISpec( title=cfg.APISPEC['title'], version=cfg.APISPEC['version'], openapi_version=cfg.APISPEC['openapi_version'], plugins=[FlaskPlugin(), MarshmallowPlugin()] ) template = spec.to_flasgger( app=app, definitions=[PlayerSchema], paths=[get_players] ) swag = Swagger(app, template=template) return app
def create_apispec(title, version, openapi_version, settings): # Create an APISpec spec = APISpec(title=title, version=version, openapi_version=openapi_version, plugins=[FlaskPlugin(), MarshmallowPlugin()], **settings) # Optional security scheme support # api_key_scheme = {"type": "apiKey", "in": "header", "name": "X-API-Key"} # spec.components.security_scheme("ApiKeyAuth", api_key_scheme) spec.components.schema("link", schema=LinkSchema).\ schema("extent", schema=ExtentSchema).\ schema("root", schema = RootSchema).\ schema("exception", schema=ExceptionSchema).\ schema("collectioninfo", schema=CollectionInfoSchema).\ schema("content", schema=ContentSchema).\ schema("req-classes", schema=ReqClassesSchema).\ schema("geometryGeoJSON", schema=GeometryGeoJSONSchema).\ schema("featureProperties", schema=FeaturePropertiesSchema) spec.components.schema("hirlamFeatureGeoJSON", schema=FeatureGeoJSONSchema) spec.components.schema("hirlamFeatureCollectionGeoJSON", schema=FeatureCollectionGeoJSONSchema) #spec.components.parameter("coll", CollectionParameter) return spec
def init_spec(app): app.spec = APISpec(openapi_version='2.0', title='Screenwriter API requirements', version='1.0.0', plugins=[FlaskPlugin(), MarshmallowPlugin()]) with app.app_context(): views = [ 'logging.get_log_file_groups', 'logging.get_log_file_raw', 'playlist.get_playlist', 'playlist.get_screen_playlist', 'pack.get_last_modified', 'pack.get_packs', 'configuration.get_complex_data', 'configuration.get_monitoring_data', 'content.get_last_modified', 'content.get_validation', 'content.get_validation_last_modified', 'content.get_cpl_xml', 'scheduling.get_last_modified', ] for view in views: app.spec.path(view=app.view_functions[view])
def create_app(): # ---------- App Configuration ---------- app = Flask(__name__) app.config.from_object( 'config.Config') # Load configurations from Config class # Init SQLAlchemy and Marshmallow db.init_app(app) ma.init_app(app) # Register Flask Blueprints app.register_blueprint(user_blueprint, url_prefix='/api/') app.register_blueprint(message_blueprint, url_prefix='/api/') # ---------- Swagger ---------- # Create an APISpec spec = APISpec(title='MessagingSystem REST API', version='1.0', openapi_version='2.0', plugins=[FlaskPlugin(), MarshmallowPlugin()]) template = spec.to_flasgger(app, definitions=[UserSchema, MessageSchema]) # Start Flasgger using a template from APISpec swag = Swagger(app, template=template) # Make Swagger the main page @app.route("/") def index(): return redirect('/apidocs/') return app
def generate_api_docs(filename, api_version, openapi_version): """ Generates swagger (openapi) yaml from routes' docstrings (using apispec library). """ from apispec import APISpec from apispec_webframeworks.flask import FlaskPlugin apidoc = APISpec( title="Grafolean API", version=api_version, openapi_version=openapi_version, plugins=[FlaskPlugin()], info={ "description": "> IMPORTANT: API is under development and is **not final yet** - breaking changes might occur.\n\n" \ "Grafolean is designed API-first. In other words, every functionality of the system is accessible through the API " \ "described below. This allows integration with external systems so that (given the permissions) they too can " \ "enter values, automatically modify entities, set up dashboards... Everything that can be done through frontend " \ "can also be achieved through API.\n\n" \ "This documentation is also available as Swagger/OpenAPI definition: [OAS2](./swagger2.yml) / [OAS3](./swagger3.yml)." } ) for apidoc_schemas_func in [users_apidoc_schemas, accounts_apidoc_schemas, admin_apidoc_schemas]: for schema_name, schema in apidoc_schemas_func(): apidoc.components.schema(schema_name, schema) with app.test_request_context(): for rule in app.url_map.iter_rules(): view = app.view_functions.get(rule.endpoint) apidoc.path(view=view) with open(filename, 'w') as openapi_yaml_file: openapi_yaml_file.write(apidoc.to_yaml())
def register_spec(test=False, test_host='localhost', test_port=12345): servers = ([{ 'url': f'http://{test_host}:{test_port}', 'description': 'Test server' }] if test else []) # Create an APISpec spec = APISpec( title='OpenReferee', version=__version__, openapi_version='3.0.2', info={ 'contact': { 'name': 'Indico Team', 'url': 'https://github.com/indico/openreferee', 'email': '*****@*****.**', } }, plugins=[FlaskPlugin(), MarshmallowPlugin()], servers=servers, tags=[{ 'name': t } for t in ('create', 'event', 'get', 'info', 'remove', 'service')], ) spec.components.security_scheme('bearer_token', { 'type': 'http', 'scheme': 'bearer' }) return spec
def __init__(self, plugin, port=10001, workers=1, threads=4, debug=False, worker_class='sync', worker_connections=200): if os.environ.get("GUNICORN_CONFIG_FILE"): with open(os.environ.get("GUNICORN_CONFIG_FILE")) as gf: self.gunicorn_config = json.load(gf) else: self.gunicorn_config = { "bind": "%s:%s" % ("0.0.0.0", port), "workers": workers, "worker_class": worker_class, "loglevel": "debug" if debug else "info", } if worker_class == 'gevent': self.gunicorn_config['worker_connections'] = worker_connections else: self.gunicorn_config['threads'] = threads super(PluginServer, self).__init__() self.plugin = plugin self.arbiter = Arbiter(self) self.logger = self.arbiter.log self.debug = debug # Create an APISpec self.spec = APISpec( title=API_TITLE, version=API_VERSION, openapi_version=OPEN_API_VERSION, plugins=[FlaskPlugin(), MarshmallowPlugin()], ) self.workers = workers self.threads = threads self.app, self.blueprints = self.create_flask_app()
def create_app(): # ---------- App Configuration ---------- app = Flask(__name__) app.config.from_object( 'config.Config') # Load configurations from Config class # Init SQLAlchemy and Marshmallow db.init_app(app) ma.init_app(app) # Register Flask Blueprints app.register_blueprint(candidate_blueprint, url_prefix='/api/') app.register_blueprint(job_blueprint, url_prefix='/api/') app.register_blueprint(skill_blueprint, url_prefix='/api/') # ---------- Swagger ---------- # Create an APISpec spec = APISpec(title='CandidateFinder REST API', version='1.0', openapi_version='2.0', plugins=[FlaskPlugin(), MarshmallowPlugin()]) template = spec.to_flasgger(app, definitions=[CandidateSchema, JobSchema]) # Set the UIVERSION to 3 app.config['SWAGGER'] = {'uiversion': 3} # Start Flasgger using a template from APISpec swag = Swagger(app, template=template) return app
def get_spec(): """ Produce the OpenAPIv3 spec document. :rtype: dict """ spec = APISpec( title="rest-demo-api", version=__version__, openapi_version="3.0.2", plugins=[FlaskPlugin(), MarshmallowPlugin()], ) app = get_app() # Useful for debugging # print(app.view_functions) spec.path("/authors", view=app.view_functions["authors"], app=app) spec.path("/authors/{author_id}", view=app.view_functions["author"], app=app) spec.path("/authors/{author_id}/quotes", view=app.view_functions["authorquotes"], app=app) spec.path("/quotes", view=app.view_functions["quotes"], app=app) spec.path("/quotes/{quote_id}", view=app.view_functions["quote"], app=app) return spec.to_dict()
def run_app( app: Flask, name: str, version: str, api_version: str, port: int, dataclasses: Optional[List[Type[JsonSchemaMixin]]] = None, print_spec: bool = False, ) -> None: spec = APISpec( title=f"{name} ({version})", version=api_version, openapi_version="3.0.2", plugins=[FlaskPlugin(), DataclassesPlugin()], ) if dataclasses is not None: for dc in dataclasses: spec.components.schema(dc.__name__, schema=dc) with app.test_request_context(): for rule in app.url_map.iter_rules(): if rule.endpoint != "static": spec.path(view=app.view_functions[rule.endpoint]) if print_spec: print(spec.to_yaml()) return @app.route("/swagger/api/swagger.json", methods=["GET"]) def get_swagger() -> str: return jsonify(spec.to_dict()) @app.errorhandler(Arcor2Exception) def handle_bad_request_general(e: Arcor2Exception) -> Tuple[str, int]: return json.dumps(str(e)), 400 @app.errorhandler(FlaskException) def handle_bad_request_intentional(e: FlaskException) -> Tuple[str, int]: return json.dumps(str(e)), e.error_code SWAGGER_URL = "/swagger" swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, "./api/swagger.json" # Swagger UI static files will be mapped to '{SWAGGER_URL}/dist/' ) # Register blueprint at URL app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) if not env.get_bool("ARCOR2_REST_API_DEBUG", False): # turn off logging each endpoint call by default log = logging.getLogger("werkzeug") log.setLevel(logging.ERROR) app.run(host="0.0.0.0", port=port)
def register_extensions(app: Flask) -> None: api.init_app(app) mongodb.init_app(app) swagger.init_app(app) spec = APISpec( title=app.config['SWAGGER']['title'], version='1.0.0', openapi_version=app.config['SWAGGER']['openapi'], plugins=[FlaskPlugin()], ) swagger.template = spec.to_flasgger(app)
def get_openapi_spec(app): spec = APISpec( title="Aleph API Documentation", version=__version__, openapi_version="3.0.2", info=spec_info, externalDocs=spec_docs, tags=spec_tags, plugins=[FlaskPlugin()], ) for name, spec_ in get_schemata().items(): spec.components.schema(name, spec_) return spec
def create_app(file_paht=file_path): app = Flask(__name__) app.config.from_pyfile(file_path) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config.update({ "APISPEC_SPEC": APISpec( title="skeleton", version="0.0.1", openapi_version="2.0.0", plugins=[FlaskPlugin(), MarshmallowPlugin()], ), "APISPEC_SWAGGER_URL": "/docs.json", "APISPEC_SWAGGER_UI_URL": "/docs/" }) docs.init_app(app) db.init_app(app) migrate.init_app(app, db, compare_type=True, compare_server_default=True) compress.init_app(app) cors.init_app(app) with app.app_context(): # set mirgration model import from main.models.board import Board from main.models.comment import Comment # Blueprint from main.controllers.board import board_bp from main.controllers.comment import comment_bp blueprints = [board_bp, comment_bp] for bp in blueprints: app.register_blueprint(bp) docs.register_existing_resources() # 스웨거에서 options 제거 for key, value in docs.spec._paths.items(): docs.spec._paths[key] = { inner_key: inner_value for inner_key, inner_value in value.items() if inner_key != "options" } return app
def _init_api_spec(self): settings = yaml.safe_load(OPENAPI_META) title = settings["info"].pop("title") spec_version = settings["info"].pop("version") openapi_version = settings.pop("openapi") spec = APISpec(title=title, version=spec_version, openapi_version=openapi_version, plugins=[FlaskPlugin(), MarshmallowPlugin()], **settings) # validate_spec(spec) return spec
def openapi_format(format="yaml", server="localhost", no_servers=False): extra_specs = { 'info': { 'description': 'The Faraday REST API enables you to interact with ' '[our server](https://github.com/infobyte/faraday).\n' 'Use this API to interact or integrate with Faraday' ' server. This page documents the REST API, with HTTP' ' response codes and example requests and responses.' }, 'security': { "ApiKeyAuth": [] } } if not no_servers: extra_specs['servers'] = [{'url': f'https://{server}/_api'}] spec = APISpec( title="Faraday API", version="2", openapi_version="3.0.2", plugins=[FaradayAPIPlugin(), FlaskPlugin(), MarshmallowPlugin()], **extra_specs) api_key_scheme = { "type": "apiKey", "in": "header", "name": "Authorization" } spec.components.security_scheme("API_KEY", api_key_scheme) response_401_unauthorized = { "description": "You are not authenticated or your API key is missing " "or invalid" } spec.components.response("UnauthorizedError", response_401_unauthorized) with app.test_request_context(): for endpoint in app.view_functions: spec.path(view=app.view_functions[endpoint], app=app) if format.lower() == "yaml": print(spec.to_yaml()) else: print(json.dumps(spec.to_dict(), indent=2))
def _register_openapi(app): from ursh.schemas import TokenSchema, URLSchema with app.app_context(): spec = APISpec( openapi_version='3.0.2', title='ursh - URL Shortener', version='2.0', plugins=( FlaskPlugin(), MarshmallowPlugin(), ), ) spec.components.schema('Token', schema=TokenSchema) spec.components.schema('URL', schema=URLSchema) app.config['APISPEC_SPEC'] = spec apispec = FlaskApiSpec(app) apispec.register_existing_resources()
def swag_init(app): # Create an APISpec spec = APISpec(title='Messaging App', version='1.0', openapi_version='2.0', plugins=[FlaskPlugin(), MarshmallowPlugin()]) template = spec.to_flasgger( app, definitions=[MessageSchema], ) # set the UIVERSION to 3 app.config['SWAGGER'] = {'uiversion': 3} # start Flasgger using a template from apispec swag = Swagger(app, template=template) return swag
def _init_api(self): # Create an APISpec self.apispec = APISpec( title='Shepherd', version=__version__, openapi_version='3.0.0', plugins=[ FlaskPlugin(), MarshmallowPlugin(), ], ) self.apispec.components.schema('FlockId', schema=FlockIdSchema) self.apispec.components.schema('FlockRequestOpts', schema=FlockRequestOptsSchema) self.apispec.components.schema('GenericResponse', schema=GenericResponseSchema) self.apispec.components.schema('LaunchResponse', schema=LaunchResponseSchema)
def init_docs(app): ctx = app.test_request_context() ctx.push() settings = yaml.safe_load(OPENAPI_SPEC) # Create an APISpec spec = APISpec( title="Swagger Project", version="1.0.0", openapi_version="3.0.2", plugins=[FlaskPlugin()], **settings ) setup_schema_definition(spec) setup_path(spec) with open("project/docs/swagger.yml", "w") as swagger_file: swagger_file.write(spec.to_yaml()) app.config["SWAGGER"] = {"title": "Swagger Project", "openapi": "3.0.2"} Swagger(app, template=spec.to_dict())
def initialize_routes(api): api.register_blueprint(comics, url_prefix='/comics') api.register_blueprint(docs) with api.test_request_context(): for r in api.url_map.iter_rules(): view = api.view_functions.get(r.endpoint) operations = load_operations_from_docstring(view.__doc__) path = FlaskPlugin.flaskpath2openapi(r.rule) if not operations: continue # De-reference the schemas referenced in the docstring. for verb in operations: resp = operations.get(verb).get('responses') for status in resp: val = resp.get(status) content = resp.get(status).get('schema') if content: pass # Add paths to the spec spec.path(view=view, path=path, operations=operations)
def _add_resource_spec(self, resource: Resource.__class__, root_name: str = None): """ Register resource """ method_name = resource.__name__.lower() method_view = self.app.view_functions[method_name] with self.app.test_request_context(): # self.spec.add_path(resource=resource, api=application.api) self.spec.path(view=method_view) if root_name is not None: path = FlaskPlugin().path_helper(view=method_view, operations=OrderedDict()) spec_path = self.spec._paths[path] for op_name in spec_path: if "tags" not in spec_path[op_name]: spec_path[op_name]["tags"] = [root_name]
def configure_openapi_with_flask(app: Flask): spec = APISpec( title="Python API", # noqa version=__version__, # noqa openapi_version="2.0", # noqa plugins=[ # noqa FlaskPlugin(), MarshmallowPlugin(), ], ) template = spec.to_flasgger( app, definitions=[ LivenessSchema, HealthCheckSchema, UserSchema, ], ) Swagger(app, template=template)
def generate_openapi(service_name: str, version: str, rpcs: List[Type[RPC]], events: List[Type[Event]]) -> str: """Generate OpenAPI models from RPCs and events. Be aware: it modifies __name__ attribute! """ # Create an APISpec spec = APISpec( title=f"{service_name} Data Models", version=version, openapi_version="3.0.2", plugins=[FlaskPlugin(), DataclassesPlugin()], ) for obj in events: if obj is Event: continue _rename_childs(obj) for rpc in rpcs: if rpc is RPC: continue for cls in (rpc.Request, rpc.Response): cls.__name__ = rpc.__name__ + cls.__name__ _rename_childs(cls) for obj in events: _add_to_spec(spec, obj) for rpc in rpcs: for cls in (rpc.Request, rpc.Response): _add_to_spec(spec, cls) return spec.to_yaml()
def get(): spec = APISpec(title="Todos", version="0.1.0", openapi_version="3.0.2", info={"description": "Todos API"}, plugins=[FlaskPlugin(), MarshmallowPlugin()]) spec.path(view=User.collection_view) spec.path(view=Login.collection_view) spec.path(view=Logout.collection_view) spec.path(view=TodoList.collection_view) spec.path(view=TodoList.view) spec.path(view=TodoList.permission_view) spec.path(view=Task.collection_view) spec.path(view=Task.view) spec.path(view=Task.reparent_view) return jsonify(spec.to_dict())
def generate_doc(): print("Generating doc...") spec = APISpec( title="RateMyProfessorAPI", version="1.0.0", openapi_version="2.0", info=dict( description= "An API that scraped Rate My Professor's Website built on Flask"), servers=[ dict(description="Main API", url="https://rate-my-professor-api.herokuapp.com/") ], tags=[ dict(name="Professors", description= "For getting professors and details about professors"), dict(name="Reviews", description="For getting all reviews") ], plugins=[FlaskPlugin(), MarshmallowPlugin()]) spec.components.schema("Professor", schema=ProfessorSchema) spec.components.schema("Review", schema=ReviewSchema) with app.test_request_context(): for function_name in app.view_functions: if function_name == 'static': continue view_function = app.view_functions[function_name] spec.path(view=view_function) with open('swagger.json', 'w') as f: json.dump(spec.to_dict(), f) @app.route('/swagger.json') def create_swagger_spec(): return jsonify(spec.to_dict())
def get_apispec(app): """ Формируем объект APISpec. :param app: объект Flask приложения """ spec = APISpec( title="My App", version="1.0.0", openapi_version="3.0.3", plugins=[FlaskPlugin(), MarshmallowPlugin()], ) spec.components.schema("Input", schema=InputSchema) spec.components.schema("Output", schema=OutputSchema) spec.components.schema("Error", schema=ErrorSchema) create_tags(spec) load_docstrings(spec, app) write_yaml_file(spec) return spec
def configure_spec(app): ma.init_app(app) app.config['SWAGGER'] = {'uiversion': 3} spec = APISpec( title='Private Identity Server', version='0.0.0', openapi_version='2.0', plugins=[ FlaskPlugin(), MarshmallowPlugin(), ], ) template = spec.to_flasgger(app, definitions=definitions) template['securityDefinitions'] = { 'basicAuth': { 'type': 'basic' }, 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' } } Swagger(app, template=template)