flask_restful.Api

Here are the examples of the python api flask_restful.Api taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

67 Examples 7

Page 1 Selected Page 2

Example 1

Project: flask-restful Source File: test_api.py
Function: test_json_with_no_settings
    def test_json_with_no_settings(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Foo(flask_restful.Resource):
            def get(self):
                return {'foo': 'bar'}

        api.add_resource(Foo, '/foo')

        with app.test_client() as client:
            data = client.get('/foo').data

        expected = b'{"foo": "bar"}\n'
        self.assertEquals(data, expected)

Example 2

Project: flask-restful Source File: test_api_with_blueprint.py
    def test_url_with_api_prefix(self):
        blueprint = Blueprint('test', __name__)
        api = flask_restful.Api(blueprint, prefix='/api')
        api.add_resource(HelloWorld, '/hi', endpoint='hello')
        app = Flask(__name__)
        app.register_blueprint(blueprint)
        with app.test_request_context('/api/hi'):
            self.assertEquals(request.endpoint, 'test.hello')

Example 3

Project: flask-restful Source File: test_api.py
Function: test_media_types_q
    def test_media_types_q(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo", headers={
            'Accept': 'application/json; q=1, application/xml; q=.5'
        }):
            self.assertEquals(api.mediatypes(),
                              ['application/json', 'application/xml'])

Example 4

Project: flask-restful Source File: test_api.py
Function: test_url_for
    def test_url_for(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        api.add_resource(HelloWorld, '/ids/<int:id>')
        with app.test_request_context('/foo'):
            self.assertEqual(api.url_for(HelloWorld, id=123), '/ids/123')

Example 5

Project: flask-restful Source File: test_api.py
Function: test_add_the_same_resource_on_same_endpoint
    def test_add_the_same_resource_on_same_endpoint(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return 'foo1'

        api.add_resource(Foo1, '/foo', endpoint='bar')
        api.add_resource(Foo1, '/foo/toto', endpoint='blah')

        with app.test_client() as client:
            foo1 = client.get('/foo')
            self.assertEquals(foo1.data, b'"foo1"\n')
            foo2 = client.get('/foo/toto')
            self.assertEquals(foo2.data, b'"foo1"\n')

Example 6

Project: flask-restful Source File: test_api.py
Function: test_handle_error
    def test_handle_error(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo"):
            resp = api.handle_error(BadRequest())
            self.assertEquals(resp.status_code, 400)
            self.assertEquals(resp.data.decode(), dumps({
                'message': BadRequest.description,
            }) + "\n")

Example 7

Project: flask-restful Source File: test_api_with_blueprint.py
Function: test_api_base
    def test_api_base(self):
        blueprint = Blueprint('test', __name__)
        api = flask_restful.Api(blueprint)
        app = Flask(__name__)
        app.register_blueprint(blueprint)
        self.assertEquals(api.urls, {})
        self.assertEquals(api.prefix, '')
        self.assertEquals(api.default_mediatype, 'application/json')

Example 8

Project: flask-restful Source File: test_api.py
Function: test_api_base
    def test_api_base(self):
        app = Mock()
        app.configure_mock(**{'record.side_effect': AttributeError})
        api = flask_restful.Api(app)
        self.assertEquals(api.urls, {})
        self.assertEquals(api.prefix, '')
        self.assertEquals(api.default_mediatype, 'application/json')

Example 9

Project: flask-restful Source File: test_api_with_blueprint.py
    def test_registration_prefix_overrides_blueprint_prefix(self):
        blueprint = Blueprint('test', __name__, url_prefix='/bp')
        api = flask_restful.Api(blueprint)
        api.add_resource(HelloWorld, '/hi', endpoint='hello')
        app = Flask(__name__)
        app.register_blueprint(blueprint, url_prefix='/reg')
        with app.test_request_context('/reg/hi'):
            self.assertEquals(request.endpoint, 'test.hello')

Example 10

Project: flask-restful Source File: test_api.py
Function: test_handle_server_error
    def test_handle_server_error(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo"):
            resp = api.handle_error(Exception())
            self.assertEquals(resp.status_code, 500)
            self.assertEquals(resp.data.decode(), dumps({
                "message": "Internal Server Error"
            }) + "\n")

Example 11

Project: flask-restful Source File: test_api.py
Function: test_output_func
    def test_output_func(self):

        def make_empty_resposne():
            return flask.make_response('')

        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo"):
            wrapper = api.output(make_empty_resposne)
            resp = wrapper()
            self.assertEquals(resp.status_code, 200)
            self.assertEquals(resp.data.decode(), '')

Example 12

Project: flask-restful Source File: test_api.py
Function: test_resource_decorator
    def test_resource_decorator(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_restful.Api(app)
        api.output = Mock()

        @api.resource('/foo', endpoint='bar')
        class Foo(flask_restful.Resource):
            pass

        app.add_url_rule.assert_called_with('/foo',
                                            view_func=api.output())

Example 13

Project: flask-restful Source File: test_api.py
Function: test_handle_non_api_error
    def test_handle_non_api_error(self):
        app = Flask(__name__)
        flask_restful.Api(app)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(resp.status_code, 404)
        self.assertEquals('text/html', resp.headers['Content-Type'])

Example 14

Project: flask-restful Source File: test_api.py
Function: test_fr_405
    def test_fr_405(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        api.add_resource(HelloWorld, '/ids/<int:id>', endpoint="hello")
        app = app.test_client()
        resp = app.post('/ids/3')
        self.assertEquals(resp.status_code, 405)
        self.assertEquals(resp.content_type, api.default_mediatype)
        # Allow can be of the form 'GET, PUT, POST'
        allow = ', '.join(set(resp.headers.get_all('Allow')))
        allow = set(method.strip() for method in allow.split(','))
        self.assertEquals(allow,
                          set(['HEAD', 'OPTIONS'] + HelloWorld.methods))

Example 15

Project: flask-restful Source File: test_api.py
    def test_handle_error_does_not_swallow_exceptions(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        exception = BadRequest('x')

        with app.test_request_context('/foo'):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 400)
            self.assertEquals(resp.get_data(), b'{"message": "x"}\n')

Example 16

Project: flask-restful Source File: test_api.py
    def test_json_float_marshalled(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class FooResource(flask_restful.Resource):
            fields = {'foo': flask_restful.fields.Float}
            def get(self):
                return flask_restful.marshal({"foo": 3.0}, self.fields)

        api.add_resource(FooResource, '/api')

        app = app.test_client()
        resp = app.get('/api')
        self.assertEquals(resp.status_code, 200)
        self.assertEquals(resp.data.decode('utf-8'), '{"foo": 3.0}\n')

Example 17

Project: flask-restful Source File: test_api.py
Function: test_media_types
    def test_media_types(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo", headers={
            'Accept': 'application/json'
        }):
            self.assertEquals(api.mediatypes(), ['application/json'])

Example 18

Project: flask-restful Source File: test_api_with_blueprint.py
Function: test_add_resource_endpoint
    def test_add_resource_endpoint(self):
        blueprint = Blueprint('test', __name__)
        api = flask_restful.Api(blueprint)
        view = Mock(**{'as_view.return_value': Mock(__name__='test_view')})
        api.add_resource(view, '/foo', endpoint='bar')
        app = Flask(__name__)
        app.register_blueprint(blueprint)
        view.as_view.assert_called_with('bar')

Example 19

Project: flask-restful Source File: test_api.py
Function: test_unauthorized_custom_realm
    def test_unauthorized_custom_realm(self):
        app = Flask(__name__)
        app.config['HTTP_BASIC_AUTH_REALM'] = 'Foo'
        api = flask_restful.Api(app, serve_challenge_on_401=True)
        response = Mock()
        response.headers = {}
        with app.test_request_context('/foo'):
            response = api.unauthorized(response)
        self.assertEquals(response.headers['WWW-Authenticate'], 'Basic realm="Foo"')

Example 20

Project: flask-restful Source File: test_api_with_blueprint.py
    def test_url_with_registration_prefix(self):
        blueprint = Blueprint('test', __name__)
        api = flask_restful.Api(blueprint)
        api.add_resource(HelloWorld, '/hi', endpoint='hello')
        app = Flask(__name__)
        app.register_blueprint(blueprint, url_prefix='/reg')
        with app.test_request_context('/reg/hi'):
            self.assertEquals(request.endpoint, 'test.hello')

Example 21

Project: flask-restful Source File: test_api.py
Function: test_add_resource_endpoint
    def test_add_resource_endpoint(self):
        app = Mock()
        app.view_functions = {}
        view = Mock()

        api = flask_restful.Api(app)
        api.output = Mock()
        api.add_resource(view, '/foo', endpoint='bar')

        view.as_view.assert_called_with('bar')

Example 22

Project: flask-restful Source File: test_api.py
Function: test_add_two_conflicting_resources_on_same_endpoint
    def test_add_two_conflicting_resources_on_same_endpoint(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Foo1(flask_restful.Resource):
            def get(self):
                return 'foo1'

        class Foo2(flask_restful.Resource):
            def get(self):
                return 'foo2'

        api.add_resource(Foo1, '/foo', endpoint='bar')
        self.assertRaises(ValueError, api.add_resource, Foo2, '/foo/toto', endpoint='bar')

Example 23

Project: flask-restful Source File: test_api.py
    def test_handle_error_401_no_challenge_by_default(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context('/foo'):
            resp = api.handle_error(Unauthorized())
            self.assertEquals(resp.status_code, 401)
            assert_false('WWW-Autheneticate' in resp.headers)

Example 24

Project: flask-restful Source File: test_api.py
    def test_add_resource(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_restful.Api(app)
        api.output = Mock()
        api.add_resource(views.MethodView, '/foo')

        app.add_url_rule.assert_called_with('/foo',
                                            view_func=api.output())

Example 25

Project: flask-restful Source File: test_api.py
Function: test_handle_error_with_code
    def test_handle_error_with_code(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, serve_challenge_on_401=True)

        exception = Exception()
        exception.code = "Not an integer"
        exception.data = {'foo': 'bar'}

        with app.test_request_context("/foo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 500)
            self.assertEquals(resp.data.decode(), dumps({"foo": "bar"}) + "\n")

Example 26

Project: flask-restful Source File: test_api.py
Function: test_output_unpack
    def test_output_unpack(self):

        def make_empty_response():
            return {'foo': 'bar'}

        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo"):
            wrapper = api.output(make_empty_response)
            resp = wrapper()
            self.assertEquals(resp.status_code, 200)
            self.assertEquals(resp.data.decode(), '{"foo": "bar"}\n')

Example 27

Project: flask-restful Source File: test_api.py
    def test_add_resource_kwargs(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_restful.Api(app)
        api.output = Mock()
        api.add_resource(views.MethodView, '/foo', defaults={"bar": "baz"})

        app.add_url_rule.assert_called_with('/foo',
                                            view_func=api.output(),
                                            defaults={"bar": "baz"})

Example 28

Project: flask-restful Source File: test_api.py
Function: test_handle_api_error
    def test_handle_api_error(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Test(flask_restful.Resource):
            def get(self):
                flask.abort(404)

        api.add_resource(Test(), '/api', endpoint='api')
        app = app.test_client()

        resp = app.get("/api")
        assert_equals(resp.status_code, 404)
        assert_equals('application/json', resp.headers['Content-Type'])
        data = loads(resp.data.decode())
        assert_true('message' in data)

Example 29

Project: flask-restful Source File: test_api.py
Function: test_end_points
    def test_endpoints(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        api.add_resource(HelloWorld, '/ids/<int:id>', endpoint="hello")
        with app.test_request_context('/foo'):
            self.assertFalse(api._has_fr_route())

        with app.test_request_context('/ids/3'):
            self.assertTrue(api._has_fr_route())

Example 30

Project: flask-restful Source File: test_api.py
    def test_handle_error_401_sends_challege_configured_realm(self):
        app = Flask(__name__)
        app.config['HTTP_BASIC_AUTH_REALM'] = 'test-realm'
        api = flask_restful.Api(app, serve_challenge_on_401=True)

        with app.test_request_context('/foo'):
            resp = api.handle_error(Unauthorized())
            self.assertEquals(resp.status_code, 401)
            self.assertEquals(resp.headers['WWW-Authenticate'],
                              'Basic realm="test-realm"')

Example 31

Project: flask-restful Source File: test_api.py
Function: test_url_for_with_blueprint
    def test_url_for_with_blueprint(self):
        """Verify that url_for works when an Api object is mounted on a
        Blueprint.
        """
        api_bp = Blueprint('api', __name__)
        app = Flask(__name__)
        api = flask_restful.Api(api_bp)
        api.add_resource(HelloWorld, '/foo/<string:bar>')
        app.register_blueprint(api_bp)
        with app.test_request_context('/foo'):
            self.assertEqual(api.url_for(HelloWorld, bar='baz'), '/foo/baz')

Example 32

Project: flask-restful Source File: test_api.py
Function: test_non_api_error_404_catchall
    def test_non_api_error_404_catchall(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, catch_all_404s=True)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(api.default_mediatype, resp.headers['Content-Type'])

Example 33

Project: flask-restful Source File: test_api.py
    def test_exception_header_forwarding_doesnt_duplicate_headers(self):
        """Test that HTTPException's headers do not add a duplicate
        Content-Length header

        https://github.com/flask-restful/flask-restful/issues/534
        """
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context('/'):
            r = api.handle_error(BadRequest())

        self.assertEqual(len(r.headers.getlist('Content-Length')), 1)

Example 34

Project: flask-restful Source File: test_api.py
    def test_unauthorized(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, serve_challenge_on_401=True)
        response = Mock()
        response.headers = {}
        with app.test_request_context('/foo'):
            response = api.unauthorized(response)
        self.assertEquals(response.headers['WWW-Authenticate'],
                          'Basic realm="flask-restful"')

Example 35

Project: flask-restful Source File: test_api.py
Function: test_redirect
    def test_redirect(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class FooResource(flask_restful.Resource):
            def get(self):
                return redirect('/')

        api.add_resource(FooResource, '/api')

        app = app.test_client()
        resp = app.get('/api')
        self.assertEquals(resp.status_code, 302)
        self.assertEquals(resp.headers['Location'], 'http://localhost/')

Example 36

Project: flask-restful Source File: test_api.py
Function: test_error_router_falls_back_to_original
    def test_error_router_falls_back_to_original(self):
        """Verify that if an exception occurs in the Flask-RESTful error handler,
        the error_router will call the original flask error handler instead.
        """
        app = Flask(__name__)
        api = flask_restful.Api(app)
        app.handle_exception = Mock()
        api.handle_error = Mock(side_effect=Exception())
        api._has_fr_route = Mock(return_value=True)
        exception = Mock(spec=HTTPException)

        with app.test_request_context('/foo'):
            api.error_router(exception, app.handle_exception)

        self.assertTrue(app.handle_exception.called_with(exception))

Example 37

Project: flask-restful Source File: test_api.py
Function: test_calling_owns_endpoint_before_api_init
    def test_calling_owns_endpoint_before_api_init(self):
        api = flask_restful.Api()

        try:
            api.owns_endpoint('endpoint')
        except AttributeError as ae:
            self.fail(ae.message)

Example 38

Project: flask-restful Source File: test_api.py
Function: test_api_representation
    def test_api_representation(self):
        app = Mock()
        api = flask_restful.Api(app)

        @api.representation('foo')
        def foo():
            pass

        self.assertEquals(api.representations['foo'], foo)

Example 39

Project: flask-restful Source File: test_api_with_blueprint.py
Function: test_api_delayed_initialization
    def test_api_delayed_initialization(self):
        blueprint = Blueprint('test', __name__)
        api = flask_restful.Api()
        api.init_app(blueprint)
        app = Flask(__name__)
        app.register_blueprint(blueprint)
        api.add_resource(HelloWorld, '/', endpoint="hello")

Example 40

Project: flask-restful Source File: test_api.py
Function: test_media_types_method
    def test_media_types_method(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        with app.test_request_context("/foo", headers={
            'Accept': 'application/xml; q=.5'
        }):
            self.assertEquals(api.mediatypes_method()(Mock()),
                              ['application/xml', 'application/json'])

Example 41

Project: flask-restful Source File: test_api_with_blueprint.py
Function: test_add_resource_endpoint_after_registration
    def test_add_resource_endpoint_after_registration(self):
        blueprint = Blueprint('test', __name__)
        api = flask_restful.Api(blueprint)
        app = Flask(__name__)
        app.register_blueprint(blueprint)
        view = Mock(**{'as_view.return_value': Mock(__name__='test_view')})
        api.add_resource(view, '/foo', endpoint='bar')
        view.as_view.assert_called_with('bar')

Example 42

Project: cloudify-manager Source File: server.py
    def __init__(self, load_config=True):
        _detect_debug_environment()
        super(CloudifyFlaskApp, self).__init__(__name__)
        if load_config:
            config.instance.load_configuration()

        # These two need to be called after the configuration was loaded
        setup_logger(self.logger, 'manager_rest')
        configure_ldap() if configure_ldap else None

        self.before_request(log_request)
        self.before_request(maintenance_mode_handler)
        self.after_request(log_response)

        self._set_exception_handlers()
        self._set_sql_alchemy()
        self._set_flask_security()

        setup_resources(Api(self))

Example 43

Project: flask-restful Source File: test_api_with_blueprint.py
    def test_url_with_blueprint_prefix(self):
        blueprint = Blueprint('test', __name__, url_prefix='/bp')
        api = flask_restful.Api(blueprint)
        api.add_resource(HelloWorld, '/hi', endpoint='hello')
        app = Flask(__name__)
        app.register_blueprint(blueprint)
        with app.test_request_context('/bp/hi'):
            self.assertEquals(request.endpoint, 'test.hello')

Example 44

Project: flask-restful Source File: test_api.py
Function: test_decorator
    def test_decorator(self):
        def return_zero(func):
            return 0

        app = Mock(flask.Flask)
        app.view_functions = {}
        view = Mock()
        api = flask_restful.Api(app)
        api.decorators.append(return_zero)
        api.output = Mock()
        api.add_resource(view, '/foo', endpoint='bar')

        app.add_url_rule.assert_called_with('/foo', view_func=0)

Example 45

Project: flask-restful Source File: test_api.py
Function: test_api_delayed_initialization
    def test_api_delayed_initialization(self):
        app = Flask(__name__)
        api = flask_restful.Api()
        api.add_resource(HelloWorld, '/', endpoint="hello")
        api.init_app(app)
        with app.test_client() as client:
            self.assertEquals(client.get('/').status_code, 200)

Example 46

Project: postgraas_server Source File: create_app.py
Function: create_app
def create_app(config):
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = get_meta_db_config_path(config)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    restful_api = Api(app)
    restful_api.add_resource(DBInstanceResource, "/api/v2/postgraas_instances/<int:id>")
    restful_api.add_resource(DBInstanceCollectionResource, "/api/v2/postgraas_instances")
    db.init_app(app)
    return app

Example 47

Project: flask-restful Source File: test_api.py
    def test_unauthorized_no_challenge_by_default(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)
        response = Mock()
        response.headers = {}
        with app.test_request_context('/foo'):
            response = api.unauthorized(response)
        assert_false('WWW-Authenticate' in response.headers)

Example 48

Project: flask-restful Source File: test_api.py
Function: test_handle_error_401_sends_challege_default_realm
    def test_handle_error_401_sends_challege_default_realm(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, serve_challenge_on_401=True)
        exception = HTTPException()
        exception.code = 401
        exception.data = {'foo': 'bar'}

        with app.test_request_context('/foo'):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 401)
            self.assertEquals(resp.headers['WWW-Authenticate'],
                              'Basic realm="flask-restful"')

Example 49

Project: flask-restful Source File: test_api.py
    def test_handle_auth(self):
        app = Flask(__name__)
        api = flask_restful.Api(app, serve_challenge_on_401=True)

        with app.test_request_context("/foo"):
            resp = api.handle_error(Unauthorized())
            self.assertEquals(resp.status_code, 401)
            expected_data = dumps({'message': Unauthorized.description}) + "\n"
            self.assertEquals(resp.data.decode(), expected_data)

            self.assertTrue('WWW-Authenticate' in resp.headers)

Example 50

Project: flask-restful Source File: test_api.py
Function: test_add_resource_forward_resource_class_parameters
    def test_add_resource_forward_resource_class_parameters(self):
        app = Flask(__name__)
        api = flask_restful.Api(app)

        class Foo(flask_restful.Resource):
            def __init__(self, *args, **kwargs):
                self.one = args[0]
                self.two = kwargs['secret_state']

            def get(self):
                return "{0} {1}".format(self.one, self.two)

        api.add_resource(Foo, '/foo',
                resource_class_args=('wonderful',),
                resource_class_kwargs={'secret_state': 'slurm'})

        with app.test_client() as client:
            foo = client.get('/foo')
            self.assertEquals(foo.data, b'"wonderful slurm"\n')
See More Examples - Go to Next Page
Page 1 Selected Page 2