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
3
Example 1
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)
3
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')
3
Example 3
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'])
3
Example 4
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')
3
Example 5
Project: flask-restful Source File: test_api.py
Function: test_add_the_same_resource_on_same_endpoint
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')
3
Example 6
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")
3
Example 7
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')
3
Example 8
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')
3
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')
3
Example 10
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")
3
Example 11
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(), '')
3
Example 12
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())
3
Example 13
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'])
3
Example 14
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))
3
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')
3
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')
3
Example 17
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'])
3
Example 18
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')
3
Example 19
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"')
3
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')
3
Example 21
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')
3
Example 22
Project: flask-restful Source File: test_api.py
Function: test_add_two_conflicting_resources_on_same_endpoint
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')
3
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)
3
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())
3
Example 25
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")
3
Example 26
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')
3
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"})
3
Example 28
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)
3
Example 29
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())
3
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"')
3
Example 31
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')
3
Example 32
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'])
3
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)
3
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"')
3
Example 35
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/')
3
Example 36
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))
3
Example 37
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)
3
Example 38
def test_api_representation(self):
app = Mock()
api = flask_restful.Api(app)
@api.representation('foo')
def foo():
pass
self.assertEquals(api.representations['foo'], foo)
3
Example 39
Project: flask-restful Source File: test_api_with_blueprint.py
Function: test_api_delayed_initialization
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")
3
Example 40
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'])
3
Example 41
Project: flask-restful Source File: test_api_with_blueprint.py
Function: test_add_resource_endpoint_after_registration
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')
3
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))
3
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')
3
Example 44
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)
3
Example 45
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)
3
Example 46
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
3
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)
3
Example 48
Project: flask-restful Source File: test_api.py
Function: test_handle_error_401_sends_challege_default_realm
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"')
3
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)
3
Example 50
Project: flask-restful Source File: test_api.py
Function: test_add_resource_forward_resource_class_parameters
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')