def register_apispec(app): from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from flask_apispec.extension import FlaskApiSpec app.config.update({ 'APISPEC_SPEC': APISpec( title='<%= app_module %>', version='v0.1.0', openapi_version='2.0', plugins=[MarshmallowPlugin()], ), 'APISPEC_SWAGGER_URL': '/spec-json', 'APISPEC_SWAGGER_UI_URL': '/spec' }) spec = FlaskApiSpec(app) spec.register(home.home, blueprint='home') <%= unless bare do %> spec.register(user.index, blueprint='user') spec.register(user.create, blueprint='user') spec.register(user.show, blueprint='user') spec.register(user.update, blueprint='user') spec.register(user.delete, blueprint='user') spec.register(session.create, blueprint='session') spec.register(session.delete, blueprint='session') <% end %>
def test_apispec_config(self, app): app.config['APISPEC_TITLE'] = 'test-extension' app.config['APISPEC_VERSION'] = '2.1' docs = FlaskApiSpec(app) assert docs.spec.info == { 'title': 'test-extension', 'version': '2.1', }
def test_apispec_config(self, app): app.config['APISPEC_TITLE'] = 'test-extension' app.config['APISPEC_VERSION'] = '2.1' app.config['APISPEC_OAS_VERSION'] = '2.0' docs = FlaskApiSpec(app) assert docs.spec.title == 'test-extension' assert docs.spec.version == '2.1' assert docs.spec.openapi_version == '2.0'
def init_app(app): """Register API resources on the provided Flask application.""" def register(path, resource): app.add_url_rule(path, view_func=resource.as_view(resource.__name__)) docs.register(resource, endpoint=resource.__name__) docs = FlaskApiSpec(app) register("/submit", Submit) register("/status/<string:uuid>", Status) register("/report/<string:uuid>", Report)
def init_app(app): """Register API resources on the provided Flask application.""" def register(path, resource): app.add_url_rule(path, view_func=resource.as_view(resource.__name__)) with warnings.catch_warnings(): warnings.simplefilter("ignore") docs.register(resource, endpoint=resource.__name__) docs = FlaskApiSpec(app) app.add_url_rule('/healthz', healthz.__name__, healthz) register('/designs', DesignsResource) register('/designs/<int:design_id>', DesignResource)
def init_app(app): """Register API resources on the provided Flask application.""" def register(path, resource): app.add_url_rule(path, view_func=resource.as_view(resource.__name__)) with warnings.catch_warnings(): warnings.simplefilter("ignore") docs.register(resource, endpoint=resource.__name__) docs = FlaskApiSpec(app) register("/predictions", PredictionJobsResource) register("/predictions/<int:job_id>", PredictionJobResource) register("/predictions/export/<int:job_id>", JobExportResource) register("/products", ProductsResource)
def init_app(app): """Register API resources on the provided Flask application.""" app.add_url_rule("/healthz", view_func=healthz) app.add_url_rule("/metrics", view_func=metrics) app.add_url_rule( "/models/<int:model_id>/modify", view_func=model_modify, methods=["POST"] ) app.add_url_rule("/simulate", view_func=model_simulate, methods=["POST"]) docs = FlaskApiSpec(app) docs.register(model_modify, endpoint=model_modify.__name__) docs.register(model_simulate, endpoint=model_simulate.__name__)
def init_app(app): """Register API resources on the provided Flask application.""" def register(path, resource): app.add_url_rule(path, view_func=resource.as_view(resource.__name__)) with warnings.catch_warnings(): warnings.simplefilter("ignore") docs.register(resource, endpoint=resource.__name__) docs = FlaskApiSpec(app) app.add_url_rule("/healthz", view_func=healthz) register("/reactions", ReactionResource) register("/reactions/batch", ReactionBatchResource) register("/metabolites", MetaboliteResource) register("/metabolites/batch", MetaboliteBatchResource)
def init_docs(self): """method to bind docs with api instance.""" self.app.config.update({ 'APISPEC_SPEC': APISpec(title=self.title, version=self.version, info={'description': self.spec_description()}, plugins=self.plugins, openapi_version='2.0'), 'APISPEC_SWAGGER_URL': self.swagger_json_url, 'APISPEC_SWAGGER_UI_URL': self.swagger_url, }) return FlaskApiSpec(self.app)
def init_doc(self): """Config and init auto-docs for api version""" self.app.config.update({ 'APISPEC_SPEC': APISpec( title=self.title, version=self.version, info={'description': self.spec_description()}, plugins=self.plugins, openapi_version='2.0' ), 'APISPEC_SWAGGER_URL': self.swagger_json_url, 'APISPEC_SWAGGER_UI_URL': self.swagger_url, }) return FlaskApiSpec(self.app)
def register_docs(app): app.config.update({ 'APISPEC_SPEC': APISpec( title='RESTful API for oneapi.cc backend', version='v1', openapi_version="2.0.0", plugins=[MarshmallowPlugin()], ), 'APISPEC_SWAGGER_URL': '/swagger/', }) docs = FlaskApiSpec(app) docs.register(register_user, endpoint="register_user", blueprint="user") docs.register(login_user, blueprint="user") docs.register(get_profile, blueprint="profiles")
def test_deferred_register(self, app): blueprint = Blueprint('test', __name__) docs = FlaskApiSpec() @doc(tags=['band']) class BandResource(MethodResource): def get(self, **kwargs): return 'slowdive' blueprint.add_url_rule('/bands/<band_id>/', view_func=BandResource.as_view('band')) docs.register(BandResource, endpoint='band', blueprint=blueprint.name) app.register_blueprint(blueprint) docs.init_app(app) assert '/bands/{band_id}/' in docs.spec._paths
def docs_config(app): app.config.update({ 'APISPEC_SPEC': APISpec(title='API Tren', version='v1', plugins=[MarshmallowPlugin()], openapi_version='2.0.0'), 'APISPEC_SWAGGER_URL': '/swagger/', # URI to access API Doc JSON 'APISPEC_SWAGGER_UI_URL': '/docs/' # URI to access UI of API Doc }) docs = FlaskApiSpec(app) return docs
def swagger_setup(self, app, title: str = 'Serverless App', version: str = 'v1'): """Add swagger documentation.""" from flask_apispec.extension import FlaskApiSpec from apispec import APISpec # swagger app.config.update({ 'APISPEC_SPEC': APISpec( title=title, version=version, plugins=[MarshmallowPlugin()], ), 'APISPEC_SWAGGER_URL': '/swagger/', }) FlaskApiSpec(app)
def setup_swagger(app): app.config.update({ 'APISPEC_SPEC': APISpec(title='Flask Template', version='v1', plugins=['apispec.ext.marshmallow'], securityDefinitions={ "json-web-token": { "in": "header", "name": "Authorization", "type": "apiKey" } }, tags=[]), 'APISPEC_SWAGGER_URL': '/swagger.json' }) docs = FlaskApiSpec(app) docs.register_existing_resources()
def init_app(app): """Register API resources on the provided Flask application.""" def register(path, resource): app.add_url_rule(path, view_func=resource.as_view(resource.__name__)) with warnings.catch_warnings(): # Silence the following warning: # apispec/ext/marshmallow/common.py:145: UserWarning: Multiple # schemas resolved to the name Organism. The name has been # modified. Either manually add each of the schemas with a # different name or provide a custom schema_name_resolver. # This happens due to `exclude` usage in the schema which makes # apispec create a new model, and that's the correct behaviour. warnings.simplefilter("ignore") docs.register(resource, endpoint=resource.__name__) docs = FlaskApiSpec(app) app.add_url_rule("/healthz", view_func=healthz) register("/hello", HelloResource)
def create_app(): if os.environ.get("environment") == "production": config = ProductionConfig() else: config = DevelopmentConfig() # create and configure the app app = Flask(__name__, instance_relative_config=True) CORS(app) app.config.from_object(config) # sqlalchemy db setup app.config["SQLALCHEMY_DATABASE_URI"] = config.DATABASE_URI app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(app) # this needs to be called sometime before you interact with the database # with app.app_context(): # db.create_all() # register blueprints app.register_blueprint(hello.blueprint) # apispec app.config.update({ "APISPEC_SPEC": APISpec( title="savegroup", version="v1", plugins=[MarshmallowPlugin()], openapi_version="3.0.2", ), "APISPEC_SWAGGER_URL": "/swagger/", }) # swagger docs docs = FlaskApiSpec(app) docs.register(hello.hello, blueprint="hello_page") return app
def init_app(app): """Register API resources on the provided Flask application.""" def register(path, resource): app.add_url_rule(path, view_func=resource.as_view(resource.__name__)) with warnings.catch_warnings(): warnings.simplefilter("ignore") docs.register(resource, endpoint=resource.__name__) docs = FlaskApiSpec(app) app.add_url_rule('/healthz', healthz.__name__, healthz) app.add_url_rule('/metrics', metrics.__name__, metrics) register("/authenticate/local", LocalAuthResource) register("/authenticate/firebase", FirebaseAuthResource) register("/refresh", RefreshResource) register("/keys", PublicKeysResource) register("/projects", ProjectsResource) register("/projects/<project_id>", ProjectResource) register("/user", UserResource) register("/user", UserRegisterResource) register("/consent", ConsentResource) register("/password/reset-request", ResetRequestResource) register("/password/reset/<token>", PasswordResetResource)
def create_app(): app = Flask(__name__) app.config['JWT_SECRET_KEY'] = JWT_SECRET_KEY JWTManager(app) app.config.update({ 'APISPEC_SPEC': APISpec( title='Wishlist API', version='v1', plugins=[MarshmallowPlugin()], openapi_version='2.0.0', info={ 'description': 'REST API to manage customers and their wishlists.' }, securityDefinitions={ 'JWT': { 'type': 'apiKey', 'in': 'header', 'name': 'Authorization' } }, ), 'APISPEC_SWAGGER_URL': '/swagger/', }) docs = FlaskApiSpec(app) start_mappers() register_urls(app, docs) app.register_error_handler(Exception, handle_exception) return app
def create_app(script_info=None): # instantiate the app app = Flask( __name__, template_folder='templates', static_folder='static' ) # sys.modules[__name__]._current_app = app # set config app_settings = os.getenv("FLASK_APP_CONFIG", "qctrl_api.config.DevelopmentConfig") app.config.from_object(app_settings) app.config.update({ 'APISPEC_SPEC': APISpec( title='Q-CTRL API', info=qdict( # description=open('API.md').read(), ), basePath="/api", version=__version__, plugins=[ # FlaskPlugin(), MarshmallowPlugin(), ], ), }) _app_logger.info("FlaskConfig: {}".format(app.config)) # Register custom error handler so we can see what is exactly failing at validation. app.errorhandler(422)(handle_unprocessable_entity) app.errorhandler(ValidationError)(handle_validation_error) # Add spec handler to app so we don't need to pass it around separately. app.docs = FlaskApiSpec(app) # set up extensions # login_manager.init_app(app) # bcrypt.init_app(app) toolbar.init_app(app) # bootstrap.init_app(app) db.init_app(app) # migrate.init_app(app, db) # CORS Plugin init CORS(app) # # flask login # from project.server.models import User # login_manager.login_view = 'user.login' # login_manager.login_message_category = 'danger' # @login_manager.user_loader # def load_user(user_id): # return User.query.filter(User.id == int(user_id)).first() # # error handlers # @app.errorhandler(401) # def unauthorized_page(error): # return render_template('errors/401.html'), 401 # @app.errorhandler(403) # def forbidden_page(error): # return render_template('errors/403.html'), 403 # @app.errorhandler(404) # def page_not_found(error): # return render_template('errors/404.html'), 404 # @app.errorhandler(500) # def server_error_page(error): # return render_template('errors/500.html'), 500 # shell context for flask cli @app.shell_context_processor def ctx(): return { "app": app, } return app
# Setup API docs and Swagger from .core import app from .auth import add_auth_to_swagger from apispec import APISpec from flask_apispec.extension import FlaskApiSpec import webargs as wa from apispec.ext.marshmallow import MarshmallowPlugin file_plugin = MarshmallowPlugin() spec = APISpec( title='neuroscout', version='v1', plugins=[file_plugin], openapi_version='2.0' ) app.config.update({ 'APISPEC_SPEC': spec}) add_auth_to_swagger(spec) docs = FlaskApiSpec(app) @file_plugin.map_to_openapi_type('file', None) class FileField(wa.fields.Raw): pass
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import scoped_session, sessionmaker from .schemas import UserSchema app = Flask(__name__) app.config.update({ "APISPEC_SPEC": APISpec(title="bank", version="v1", openapi_version="2.0", plugins=[MarshmallowPlugin()]), "APISPEC_SWAGGER_URL": "/swagger/" }) docs = FlaskApiSpec() client = app.test_client() engine = create_engine("sqlite:///bank/db.sqlite") session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = session.query_property() # importing here because of circular import error from .models import * Base.metadata.create_all(bind=engine) # place for future
def docs(app): return FlaskApiSpec(app)
def test_serve_swagger_ui_custom_url(self, app, client): app.config['APISPEC_SWAGGER_UI_URL'] = '/swagger-ui.html' FlaskApiSpec(app) client.get('/swagger-ui.html')
def test_serve_swagger_custom_url(self, app, client): app.config['APISPEC_SWAGGER_URL'] = '/swagger.json' docs = FlaskApiSpec(app) res = client.get('/swagger.json') assert res.json == docs.spec.to_dict()
for attr, value in kwargs.items(): setattr(self, attr, value) return commit and self.save() or self def save(self, commit=True): """Save the record.""" db.session.add(self) if commit: db.session.commit() return self def delete(self, commit=True): """Remove the record from the database.""" db.session.delete(self) return commit and db.session.commit() bcrypt = Bcrypt() db = SQLAlchemy(model_class=CRUDMixin) migrate = Migrate() cache = Cache() cors = CORS() docs = FlaskApiSpec(document_options=False) api = Api(prefix='/api') from src.utils import jwt_identity, identity_loader # noqa jwt = JWTManager() jwt.user_loader_callback_loader(jwt_identity) jwt.user_identity_loader(identity_loader)
# title = "Name Recorder", # description = "Manage names of various users of the application") api = Api(flask_app) flask_app.config.update({ 'APISPEC_SPEC': APISpec( title='Name Recorder', description='Manage names of various users of the application', version='1.0', plugins=[MarshmallowPlugin()], openapi_version='2.0.0' ), 'APISPEC_SWAGGER_URL': '/swagger/', # URI to access API Doc JSON 'APISPEC_SWAGGER_UI_URL': '/swagger-ui/' # URI to access UI of API Doc }) app = FlaskApiSpec(flask_app) # app = Api(app=flask_app) parser = reqparse.RequestParser() parser.add_argument('id', type=int, required=True, help='id cannot be blank.') parser.add_argument('name', type=str, required=True, help='Name cannot be blank.') # class AwesomeResponseSchema(Schema): # message = fields.Str(default='Success') class put_action(Schema): id = fields.Integer(required=True, description="API type of awesome API")
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) # SWAGGER SETTINGS SWAGGER_URL = MongoApiConfig.swagger_url() API_URL = MongoApiConfig.api_url() # END SWAGGER SETTINGS app.config.update(MongoApiConfig.api_spec()) docs = FlaskApiSpec(app) mongo_data_api = MongoApi() if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass @app.route('/') def go_to_swagger(): return redirect("[apiBroadcastHttp][apiBroadcastIp]:[apiBroadcastPort]/swagger-ui", code=302) # READ ----> GET @marshal_with(ModelSchema) @app.route('/' + MongoApiConfig.api_name(), methods=['GET'], provide_automatic_options=False) def mongo_read(): response = mongo_data_api.read() return Response(response=json.dumps(response), status=200, mimetype='application/json') # READ ----> GET/ID @marshal_with(ModelSchema) @app.route('/' + MongoApiConfig.api_name() + '/<object_id>', methods=['GET'], provide_automatic_options=False) def mongo_read_by_id(object_id): response = mongo_data_api.read_by_id(object_id) return Response(response=json.dumps(response), status=200, mimetype='application/json') # CREATE ---> POST @use_kwargs(ModelSchema, location='json') @marshal_with(ModelSchema) @app.route('/' + MongoApiConfig.api_name(), methods=['POST'], provide_automatic_options=False) def mongo_write(): data = request.json if data is None or data == {}: return Response(response=json.dumps({"Error": "Please provide data to post"}), status=400, mimetype='application/json') response = mongo_data_api.write(data) return Response(response=json.dumps(response), status=200, mimetype='application/json') # UPDATE ----> PUT @use_kwargs(ModelSchema, location='json') @marshal_with(ModelSchema) @app.route('/' + MongoApiConfig.api_name() + '/<object_id>', methods=['PUT'], provide_automatic_options=False) def mongo_update(object_id): data = request.json if data is None or data == {}: return Response(response=json.dumps({"Error": "Please provide data to put"}), status=400, mimetype='application/json') response = mongo_data_api.update(object_id, data) return Response(response=json.dumps(response), status=200, mimetype='application/json') # DELETE -----> DELETE @app.route('/' + MongoApiConfig.api_name() + '/<object_id>', methods=['DELETE'], provide_automatic_options=False) def mongo_delete(object_id): if id is None or object_id == {}: return Response(response=json.dumps({"Error": "Please provide object id"}), status=400, mimetype='application/json') response = mongo_data_api.delete(object_id) return Response(response=json.dumps(response), status=200, mimetype='application/json') docs.register(mongo_read) docs.register(mongo_write) docs.register(mongo_update) docs.register(mongo_delete) docs.register(mongo_read_by_id) return app
def __init__(self, app: Flask) -> None: app.config.update({ 'APISPEC_SPEC': make_apispec(title='Flask API', version='v1'), 'APISPEC_SWAGGER_URL': '/swagger/', }) self.apispec = FlaskApiSpec(app)