Python flask_restplus.Api() Examples

The following are 19 code examples of flask_restplus.Api(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_restplus , or try the search function .
Example #1
Source File: app.py    From biggraphite with Apache License 2.0 6 votes vote down vote up
def initialize_api(self):
        """Initialize an API."""
        blueprint = flask.Blueprint("api", __name__, url_prefix="/api")

        api = flask_restplus.Api(version="1.0", title="BigGraphite API")
        api.namespaces = []
        api.add_namespace(ns_bgutil.api)
        api.add_namespace(ns_biggraphite.api)
        api.init_app(blueprint)

        self.app.register_blueprint(blueprint)

        if flask_cors:
            # Allow others to request swagger stuff without restrictions.
            # This helps for https reverse proxy with bad headers.
            flask_cors.CORS(
                self.app, resources={r"/api/swagger.json": {"origins": "*"}}) 
Example #2
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 6 votes vote down vote up
def create_app(script=False):
    from users_backend.api_namespace import api_namespace
    from users_backend.admin_namespace import admin_namespace

    application = Flask(__name__)

    if not script:
        # Initialise metrics
        metrics.init_app(application)

    api = Api(application, version=VERSION, title='Users Backend API',
              description='A Simple CRUD API')

    from users_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #3
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 6 votes vote down vote up
def create_app():
    from thoughts_backend.api_namespace import api_namespace
    from thoughts_backend.admin_namespace import admin_namespace

    application = Flask(__name__)
    api = Api(application, version='0.1', title='Thoughts Backend API',
              description='A Simple CRUD API')

    from thoughts_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #4
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 6 votes vote down vote up
def create_app(script=False):
    from users_backend.api_namespace import api_namespace
    from users_backend.admin_namespace import admin_namespace

    application = Flask(__name__)

    if not script:
        # Initialise metrics
        metrics.init_app(application)

    api = Api(application, version='0.1', title='Users Backend API',
              description='A Simple CRUD API')

    from users_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #5
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 6 votes vote down vote up
def create_app():
    from thoughts_backend.api_namespace import api_namespace
    from thoughts_backend.admin_namespace import admin_namespace

    application = Flask(__name__)
    api = Api(application, version='0.1', title='Thoughts Backend API',
              description='A Simple CRUD API')

    from thoughts_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #6
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 6 votes vote down vote up
def create_app():
    from users_backend.api_namespace import api_namespace
    from users_backend.admin_namespace import admin_namespace

    application = Flask(__name__)
    api = Api(application, version='0.1', title='Users Backend API',
              description='A Simple CRUD API')

    from users_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #7
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 6 votes vote down vote up
def create_app():
    from thoughts_backend.api_namespace import api_namespace
    from thoughts_backend.admin_namespace import admin_namespace

    application = Flask(__name__)
    api = Api(application, version='0.1', title='Thoughts Backend API',
              description='A Simple CRUD API')

    from thoughts_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #8
Source File: scheduler_test.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True
        self.app.json_encoder = rest.CompliantJsonEncoder

        api = restplus.Api(self.app)
        error_handlers.register(api)

        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)
        self.impl = mock.Mock()

        scheduler.init(api, cors, self.impl)
        self.client = self.app.test_client() 
Example #9
Source File: group_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True
        self.impl = mock.Mock()

        api = restplus.Api(self.app)
        cors = webutils.cors(
            origin='*',
            content_type='application/json',
            credentials=False,
        )
        group.init(api, cors, self.impl)

        self.client = self.app.test_client() 
Example #10
Source File: local_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True
        self.impl = mock.Mock()

        api = restplus.Api(self.app)
        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)

        error_handlers.register(api)

        local.init(api, cors, self.impl)
        self.client = self.app.test_client() 
Example #11
Source File: server_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True

        api = restplus.Api(self.app)
        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)
        self.impl = mock.Mock()

        server.init(api, cors, self.impl)
        self.client = self.app.test_client() 
Example #12
Source File: cgroup_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True

        api = restplus.Api(self.app)
        error_handlers.register(api)

        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)
        self.impl = mock.Mock()

        cgroup.init(api, cors, self.impl)
        self.client = self.app.test_client() 
Example #13
Source File: instance_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True

        api = restplus.Api(self.app)
        error_handlers.register(api)

        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)
        self.impl = mock.Mock()

        instance.init(api, cors, self.impl)
        self.client = self.app.test_client() 
Example #14
Source File: state_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True

        api = restplus.Api(self.app)
        error_handlers.register(api)

        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)
        self.impl = mock.Mock()

        state.init(api, cors, self.impl)
        self.client = self.app.test_client() 
Example #15
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 5 votes vote down vote up
def create_app(script=False):
    from thoughts_backend.api_namespace import api_namespace
    from thoughts_backend.admin_namespace import admin_namespace

    application = Flask(__name__)
    application.before_request(logging_before)
    application.after_request(logging_after)

    # Enable RequestId
    application.config['REQUEST_ID_UNIQUE_VALUE_PREFIX'] = ''
    RequestID(application)

    if not script:
        # For scripts, it should not connect to Syslog
        handler = logging.handlers.SysLogHandler(('syslog', 5140))
        req_format = ('[%(asctime)s] %(levelname)s [%(request_id)s] '
                      '%(module)s: %(message)s')
        handler.setFormatter(RequestFormatter(req_format))
        handler.setLevel(logging.INFO)
        application.logger.addHandler(handler)
        # Do not propagate to avoid log duplication
        application.logger.propagate = False

        # Initialise metrics
        metrics.init_app(application)

    api = Api(application, version='0.1', title='Thoughts Backend API',
              description='A Simple CRUD API')

    from thoughts_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #16
Source File: limit_test.py    From treadmill with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        """Initialize the app with the corresponding limit logic."""
        blueprint = flask.Blueprint('v1', __name__)
        self.api = restplus.Api(blueprint)

        self.app = flask.Flask(__name__)
        self.app.testing = True
        self.app.register_blueprint(blueprint)

        na = self.api.namespace(
            'na', description='Request Rate Control REST API Test',
        )

        @na.route('/foo')
        class _Foo(restplus.Resource):
            """Request rate control resource example"""

            def get(self):
                """Get resource implement"""
                return ''

        @na.route('/bar')
        class _Bar(restplus.Resource):
            """Request rate control resource example"""

            def get(self):
                """Get resource implement"""
                return ''

        nb = self.api.namespace(
            'nb', description='Request Rate Control REST API Test',
        )

        @nb.route('/baz')
        class _Baz(restplus.Resource):
            """Request rate control resource example"""

            def get(self):
                """Get resource implement"""
                return '' 
Example #17
Source File: app.py    From Hands-On-Docker-for-Microservices-with-Python with MIT License 5 votes vote down vote up
def create_app(script=False):
    from thoughts_backend.api_namespace import api_namespace
    from thoughts_backend.admin_namespace import admin_namespace

    application = Flask(__name__)
    application.before_request(logging_before)
    application.after_request(logging_after)

    # Enable RequestId
    application.config['REQUEST_ID_UNIQUE_VALUE_PREFIX'] = ''
    RequestID(application)

    if not script:
        # For scripts, it should not connect to Syslog
        handler = logging.handlers.SysLogHandler(('syslog', 5140))
        req_format = ('[%(asctime)s] %(levelname)s [%(request_id)s] '
                      '%(module)s: %(message)s')
        handler.setFormatter(RequestFormatter(req_format))
        handler.setLevel(logging.INFO)
        application.logger.addHandler(handler)
        # Do not propagate to avoid log duplication
        application.logger.propagate = False

        # Initialise metrics
        metrics.init_app(application)

    api = Api(application, version=VERSION, title='Thoughts Backend API',
              description='A Simple CRUD API')

    from thoughts_backend.db import db, db_config
    application.config['RESTPLUS_MASK_SWAGGER'] = False
    application.config.update(db_config)
    db.init_app(application)
    application.db = db

    api.add_namespace(api_namespace)
    api.add_namespace(admin_namespace)

    return application 
Example #18
Source File: api.py    From flask-shop with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def flaskshop_load_blueprints(app):
    bp = Blueprint("api", __name__)

    csrf_protect.exempt(bp)
    bp.session_interface = CustomSessionInterface()
    ALLOWED_PATHS = frozenset(
        ["/api/v1/user/login", "/api/v1/", "/api/v1/swagger.json", "/api/v1/products/"]
    )

    @bp.after_request
    def verify_user(response):
        from .auth import verify_token

        if request.path in ALLOWED_PATHS or request.method == "OPTIONS":
            return response
        elif "Authorization" in request.headers:
            data = verify_token(request.headers["Authorization"])
            if data:
                return response
        return "", 401

    api = Api(bp, version="1.0", title="Saleor API", description="A simple API")

    @api.errorhandler
    def default_error_handler(error):
        """Default error handler"""
        return {"message": str(error)}, getattr(error, "code", 500)

    api.add_namespace(product_api)
    api.add_namespace(checkout_api)
    api.add_namespace(auth_api)

    app.register_blueprint(bp, url_prefix="/api/v1") 
Example #19
Source File: __init__.py    From treadmill with Apache License 2.0 4 votes vote down vote up
def base_api(title=None, cors_origin=None):
    """Create base_api object"""
    blueprint = flask.Blueprint('v1', __name__)

    api = restplus.Api(blueprint, version='1.0',
                       title=title,
                       description='Treadmill REST API Documentation')

    error_handlers.register(api)

    # load up any external error_handlers
    for module in plugin_manager.load_all('treadmill.rest.error_handlers'):
        module.init(api)

    @blueprint.route('/docs/', endpoint='docs')
    def _swagger_ui():
        """Swagger documentation route"""
        return restplus.apidoc.ui_for(api)

    rest.FLASK_APP.register_blueprint(blueprint)
    rest.FLASK_APP.register_blueprint(restplus.apidoc.apidoc)

    cors = webutils.cors(origin=cors_origin,
                         content_type='application/json',
                         credentials=True)

    @rest.FLASK_APP.before_request
    def _before_request_user_handler():
        user = flask.request.environ.get('REMOTE_USER')
        if user:
            flask.g.user = user

    @rest.FLASK_APP.after_request
    def _after_request_cors_handler(response):
        """Process all OPTIONS request, thus don't need to add to each app"""
        if flask.request.method != 'OPTIONS':
            return response

        _LOGGER.debug('This is an OPTIONS call')

        def _noop_options():
            """No noop response handler for all OPTIONS.
            """

        headers = flask.request.headers.get('Access-Control-Request-Headers')
        options_cors = webutils.cors(origin=cors_origin,
                                     credentials=True,
                                     headers=headers)
        response = options_cors(_noop_options)()
        return response

    return (api, cors)