def test_marshal_with_expose_custom_mask_header(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return {'name': 'John Doe', 'age': 42, 'boolean': True} with self.settings(RESTPLUS_MASK_HEADER='X-Mask'): specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertIn('parameters', op) self.assertEqual(len(op['parameters']), 1) param = op['parameters'][0] self.assertEqual(param['name'], 'X-Mask')
def test_marshal_honour_custom_field_mask(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): def get(self): return api.marshal({ 'name': 'John Doe', 'age': 42, 'boolean': True }, model) with self.settings(RESTPLUS_MASK_HEADER='X-Mask'): data = self.get_json('/test/', headers={ 'X-Mask': '{name,age}' }) self.assertEqual(data, { 'name': 'John Doe', 'age': 42, })
def test_marshal_does_not_hit_unrequired_attributes(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) class Person(object): def __init__(self, name, age): self.name = name self.age = age @property def boolean(self): raise Exception() @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return Person('John Doe', 42) data = self.get_json('/test/', headers={ 'X-Fields': '{name,age}' }) self.assertEqual(data, { 'name': 'John Doe', 'age': 42, })
def test_marshal_with_expose_mask_header(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return {'name': 'John Doe', 'age': 42, 'boolean': True} specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertIn('parameters', op) self.assertEqual(len(op['parameters']), 1) param = op['parameters'][0] self.assertEqual(param['name'], 'X-Fields') self.assertEqual(param['type'], 'string') self.assertEqual(param['format'], 'mask') self.assertEqual(param['in'], 'header') self.assertNotIn('required', param)
def test_marshal_does_not_hit_unrequired_attributes(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) class Person(object): def __init__(self, name, age): self.name = name self.age = age @property def boolean(self): raise Exception() @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return Person('John Doe', 42) data = self.get_json('/test/', headers={'X-Fields': '{name,age}'}) self.assertEqual(data, { 'name': 'John Doe', 'age': 42, })
def test_marshal_with_expose_mask_header(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return { 'name': 'John Doe', 'age': 42, 'boolean': True } specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertIn('parameters', op) self.assertEqual(len(op['parameters']), 1) param = op['parameters'][0] self.assertEqual(param['name'], 'X-Fields') self.assertEqual(param['type'], 'string') self.assertEqual(param['format'], 'mask') self.assertEqual(param['in'], 'header') self.assertNotIn('required', param)
def test_marshal_with_honour_field_mask_list(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return [{ 'name': 'John Doe', 'age': 42, 'boolean': True }, { 'name': 'Jane Doe', 'age': 33, 'boolean': False }] data = self.get_json('/test/', headers={'X-Fields': '{name,age}'}) self.assertEqual(data, [{ 'name': 'John Doe', 'age': 42, }, { 'name': 'Jane Doe', 'age': 33, }])
def test_marshal_honour_custom_field_mask(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): def get(self): return api.marshal( { 'name': 'John Doe', 'age': 42, 'boolean': True }, model) with self.settings(RESTPLUS_MASK_HEADER='X-Mask'): data = self.get_json('/test/', headers={'X-Mask': '{name,age}'}) self.assertEqual(data, { 'name': 'John Doe', 'age': 42, })
def test_marshal_with_expose_custom_mask_header(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return { 'name': 'John Doe', 'age': 42, 'boolean': True } with self.settings(RESTPLUS_MASK_HEADER='X-Mask'): specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertIn('parameters', op) self.assertEqual(len(op['parameters']), 1) param = op['parameters'][0] self.assertEqual(param['name'], 'X-Mask')
def test_marshal_with_disabling_mask_header(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return { 'name': 'John Doe', 'age': 42, 'boolean': True } with self.settings(RESTPLUS_MASK_SWAGGER=False): specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertNotIn('parameters', op)
def test_marshal_with_honour_field_mask_list(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return [{ 'name': 'John Doe', 'age': 42, 'boolean': True }, { 'name': 'Jane Doe', 'age': 33, 'boolean': False }] data = self.get_json('/test/', headers={ 'X-Fields': '{name,age}' }) self.assertEqual(data, [{ 'name': 'John Doe', 'age': 42, }, { 'name': 'Jane Doe', 'age': 33, }])
def test_with_readonly(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, readonly=True) self.assertEqual(field.__schema__, { '$ref': '#/definitions/NestedModel', 'readOnly': True })
def test_nested_field_as_list_is_reusable(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) prop = utils.field_to_property(api.as_list(fields.Nested(nested_fields))) self.assertEqual(prop, {'type': 'array', 'items': {'$ref': 'NestedModel'}}) prop = utils.field_to_property(fields.Nested(nested_fields)) self.assertEqual(prop, {'$ref': 'NestedModel', 'required': True})
def test_models(self): app = Flask(__name__) api = Api(app) todo_fields = api.model('Todo', { 'task': fields.String(required=True, description='The task details') }) parser = reqparse.RequestParser() parser.add_argument('todo', type=todo_fields) self.assertEqual(utils.parser_to_params(parser), { 'todo': { 'type': 'Todo', 'paramType': 'body', }, })
def test_raise_400_on_invalid_mask(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): pass with self.app.test_client() as client: response = client.get('/test/', headers={'X-Fields': 'name{,missing}'}) self.assertEqual(response.status_code, 400) self.assertEquals(response.content_type, 'application/json')
def test_marshal_with_skip_missing_fields(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return { 'name': 'John Doe', 'age': 42, } data = self.get_json('/test/', headers={'X-Fields': '{name,missing}'}) self.assertEqual(data, { 'name': 'John Doe', })
def test_is_only_exposed_on_marshal_with(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): def get(self): return api.marshal({ 'name': 'John Doe', 'age': 42, 'boolean': True }, model) specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertNotIn('parameters', op)
def test_marshal_with_disabling_mask_header(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return {'name': 'John Doe', 'age': 42, 'boolean': True} with self.settings(RESTPLUS_MASK_SWAGGER=False): specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertNotIn('parameters', op)
def test_marshal_with_skip_missing_fields(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): return { 'name': 'John Doe', 'age': 42, } data = self.get_json('/test/', headers={ 'X-Fields': '{name,missing}' }) self.assertEqual(data, { 'name': 'John Doe', })
def test_is_only_exposed_on_marshal_with(self): api = Api(self.app) model = api.model( 'Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) @api.route('/test/') class TestResource(Resource): def get(self): return api.marshal( { 'name': 'John Doe', 'age': 42, 'boolean': True }, model) specs = self.get_specs() op = specs['paths']['/test/']['get'] self.assertNotIn('parameters', op)
@app.route('/api/', endpoint='api') def swagger_ui(): return apidoc.ui_for(api) @app.route('/') @app.route('/app') def hello_world(): return render_template('criteria.html') api = Api(app, version='1', title='USSC test task', ui=False) criteria_ns = api.namespace(name='Criteria', description="Запросы, связанные с критериями", path=API_PATH) input_box_ip = api.model('BoxIPInput', {'data': fields.String}) @criteria_ns.route('/criteria/<criterion_id>', endpoint='criterion') class CriterionAPI(Resource): def __init__(self): super(CriterionAPI, self).__init__() def get(self, criterion_id): u""" Получить критерий """ return { "data": { "id": "0b1c7f57-0a89-41bc-966d-474301c25bc9", "oval_id": "oval:ru.ussc:tst:3044",
'NumberOfTime60-89DaysPastDueNotWorse', type=float, required=True, help= 'Number of mortgage and real estate loans including home equity lines of credit', location='form') parser.add_argument( 'NumberOfDependents', type=float, required=True, help= 'Number of mortgage and real estate loans including home equity lines of credit', location='form') resource_fields = api.model('Resource', { 'result': fields.String, }) from flask.ext.restplus import Resource @ns.route('/') class CreditApi(Resource): @api.doc(parser=parser) @api.marshal_with(resource_fields) def post(self): args = parser.parse_args() result = self.get_result(args) return result, 201
class ModelTestCase(TestCase): def setUp(self): super(ModelTestCase, self).setUp() blueprint = Blueprint('api', __name__) self.api = Api(blueprint) self.app.register_blueprint(blueprint) def test_model_as_flat_dict(self): model = self.api.model( 'Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, }) self.assertEqual( model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' } } }) def test_model_as_nested_dict(self): address = self.api.model('Address', { 'road': fields.String, }) person = self.api.model( 'Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'address': fields.Nested(address) }) self.assertEqual( person.__schema__, { # 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'address': { '$ref': '#/definitions/Address', } } }) self.assertEqual(address.__schema__, {'properties': { 'road': { 'type': 'string' }, }}) def test_model_as_dict_with_list(self): model = self.api.model( 'Person', { 'name': fields.String, 'age': fields.Integer, 'tags': fields.List(fields.String), }) self.assertEqual( model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'tags': { 'type': 'array', 'items': { 'type': 'string' } } } }) def test_model_as_nested_dict_with_list(self): address = self.api.model('Address', { 'road': fields.String, }) person = self.api.model( 'Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'addresses': fields.List(fields.Nested(address)) }) self.assertEqual( person.__schema__, { # 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'addresses': { 'type': 'array', 'items': { '$ref': '#/definitions/Address', } } } }) self.assertEqual(address.__schema__, {'properties': { 'road': { 'type': 'string' }, }}) def test_model_with_required(self): model = self.api.model( 'Person', { 'name': fields.String(required=True), 'age': fields.Integer, 'birthdate': fields.DateTime(required=True), }) self.assertEqual( model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' } }, 'required': ['birthdate', 'name'] }) def test_model_as_nested_dict_and_required(self): address = self.api.model('Address', { 'road': fields.String, }) person = self.api.model( 'Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'address': fields.Nested(address, required=True) }) self.assertEqual( person.__schema__, { 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'address': { '$ref': '#/definitions/Address', } } }) self.assertEqual(address.__schema__, {'properties': { 'road': { 'type': 'string' }, }}) def test_model_with_discriminator(self): model = self.api.model('Person', { 'name': fields.String(discriminator=True), 'age': fields.Integer, }) self.assertEqual( model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, }, 'discriminator': 'name', 'required': ['name'] }) def test_model_with_discriminator_override_require(self): model = self.api.model( 'Person', { 'name': fields.String(discriminator=True, required=False), 'age': fields.Integer, }) self.assertEqual( model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, }, 'discriminator': 'name', 'required': ['name'] }) def test_extend(self): parent = self.api.model( 'Parent', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, }) child = self.api.extend('Child', parent, { 'extra': fields.String, }) self.assertEqual( child.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'extra': { 'type': 'string' } } }) self.assertIn('Parent', self.api.models) self.assertIn('Child', self.api.models) def test_extend_with_multiple_parents(self): grand_parent = self.api.model('GrandParent', { 'grand_parent': fields.String, }) parent = self.api.model( 'Parent', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, }) child = self.api.extend('Child', [grand_parent, parent], { 'extra': fields.String, }) self.assertEqual( child.__schema__, { 'properties': { 'grand_parent': { 'type': 'string' }, 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'extra': { 'type': 'string' } } }) self.assertIn('GrandParent', self.api.models) self.assertIn('Parent', self.api.models) self.assertIn('Child', self.api.models) def test_inherit(self): parent = self.api.model('Parent', { 'name': fields.String, 'age': fields.Integer, }) child = self.api.inherit('Child', parent, { 'extra': fields.String, }) self.assertEqual( parent.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, } }) self.assertEqual( child.__schema__, { 'allOf': [{ '$ref': '#/definitions/Parent' }, { 'properties': { 'extra': { 'type': 'string' } } }] }) self.assertIn('Parent', self.api.models) self.assertIn('Child', self.api.models) def test_inherit_inline(self): parent = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, }) child = self.api.inherit('Child', parent, { 'extra': fields.String, }) self.api.model( 'Output', { 'child': fields.Nested(child), 'children': fields.List(fields.Nested(child)) }) self.assertIn('Person', self.api.models) self.assertIn('Child', self.api.models) def test_polymorph_inherit_common_ancestor(self): class Child1: pass class Child2: pass parent = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) mapping = { Child1: child1, Child2: child2, } output = self.api.model('Output', {'child': fields.Polymorph(mapping)}) # Should use the common ancestor self.assertEqual( output.__schema__, {'properties': { 'child': { '$ref': '#/definitions/Person' }, }})
api = Api(app, version='0.1', title='Packaging-engine dummy API', description='Dummy API for the packaging-engine') namespace = api.namespace('v1', description='v1') newPackArgs = api.parser() newPackArgs.add_argument('requestToken', location='form') newPackArgs.add_argument('recipes', type=FileStorage, help='Tar archive that contains the recipes and related data following some rules.' , location='files') packprocessInfo = { 'status': fields.String, 'description': fields.String, 'percentage': fields.Integer } packprocessInfoModel = api.model('packprocessInfo', packprocessInfo) def __checkPackage__(file): if file.filename == 'validrecipes.tar': return True else: return False @namespace.route('/recipe') class PackageService(Resource): @api.doc(description='Start to packetize recipe.', parser=newPackArgs) @api.response(201, 'Created', packprocessInfoModel) def post(self): err = None
from controllers.builder import builderOps from controllers.cluster import clusterOps from controllers.composer import composeOps from controllers.management import managementOps from datastore import dataStore from datastore.dataStore import DataStore app = Flask(__name__) api = Api(app, version='0.5', title='Docker commander API', description='An unified API to all Docker operations.',) datastore = DataStore(app) # Common errorResponseModel = api.model('Error', generalSchemas.basic_error_response) def not_implemented(): result = {'error':'not_implemented', 'description':'Feature not implemented yet'} return result, 500 def not_found(): result = {'error':'not_found', 'description':'Resource not found'} return result, 404 # Extra routes extra_ns = api.namespace('extra', description='Some extra functions.') @extra_ns.route('/purge') class Purge(Resource):
class ModelTestCase(TestCase): def setUp(self): super(ModelTestCase, self).setUp() blueprint = Blueprint('api', __name__) self.api = Api(blueprint) self.app.register_blueprint(blueprint) def test_model_as_flat_dict(self): model = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, }) self.assertEqual(model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' } } }) def test_model_as_nested_dict(self): address = self.api.model('Address', { 'road': fields.String, }) person = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'address': fields.Nested(address) }) self.assertEqual(person.__schema__, { # 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'address': { '$ref': '#/definitions/Address', } } }) self.assertEqual(address.__schema__, { 'properties': { 'road': { 'type': 'string' }, } }) def test_model_as_dict_with_list(self): model = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, 'tags': fields.List(fields.String), }) self.assertEqual(model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'tags': { 'type': 'array', 'items': { 'type': 'string' } } } }) def test_model_as_nested_dict_with_list(self): address = self.api.model('Address', { 'road': fields.String, }) person = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'addresses': fields.List(fields.Nested(address)) }) self.assertEqual(person.__schema__, { # 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'addresses': { 'type': 'array', 'items': { '$ref': '#/definitions/Address', } } } }) self.assertEqual(address.__schema__, { 'properties': { 'road': { 'type': 'string' }, } }) def test_model_with_required(self): model = self.api.model('Person', { 'name': fields.String(required=True), 'age': fields.Integer, 'birthdate': fields.DateTime(required=True), }) self.assertEqual(model.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' } }, 'required': ['birthdate', 'name'] }) def test_model_as_nested_dict_and_required(self): address = self.api.model('Address', { 'road': fields.String, }) person = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, 'address': fields.Nested(address, required=True) }) self.assertEqual(person.__schema__, { 'required': ['address'], 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'address': { '$ref': '#/definitions/Address', } } }) self.assertEqual(address.__schema__, { 'properties': { 'road': { 'type': 'string' }, } }) def test_model_with_discriminator(self): model = self.api.model('Person', { 'name': fields.String(discriminator=True), 'age': fields.Integer, }) self.assertEqual(model.__schema__, { 'properties': { 'name': {'type': 'string'}, 'age': {'type': 'integer'}, }, 'discriminator': 'name', 'required': ['name'] }) def test_model_with_discriminator_override_require(self): model = self.api.model('Person', { 'name': fields.String(discriminator=True, required=False), 'age': fields.Integer, }) self.assertEqual(model.__schema__, { 'properties': { 'name': {'type': 'string'}, 'age': {'type': 'integer'}, }, 'discriminator': 'name', 'required': ['name'] }) def test_extend(self): parent = self.api.model('Parent', { 'name': fields.String, 'age': fields.Integer, 'birthdate': fields.DateTime, }) child = self.api.extend('Child', parent, { 'extra': fields.String, }) self.assertEqual(child.__schema__, { 'properties': { 'name': { 'type': 'string' }, 'age': { 'type': 'integer' }, 'birthdate': { 'type': 'string', 'format': 'date-time' }, 'extra': { 'type': 'string' } } }) self.assertIn('Parent', self.api.models) self.assertIn('Child', self.api.models) def test_inherit(self): parent = self.api.model('Parent', { 'name': fields.String, 'age': fields.Integer, }) child = self.api.inherit('Child', parent, { 'extra': fields.String, }) self.assertEqual(parent.__schema__, { 'properties': { 'name': {'type': 'string'}, 'age': {'type': 'integer'}, } }) self.assertEqual(child.__schema__, { 'allOf': [{ '$ref': '#/definitions/Parent' }, { 'properties': { 'extra': {'type': 'string'} } } ] }) self.assertIn('Parent', self.api.models) self.assertIn('Child', self.api.models) def test_inherit_inline(self): parent = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, }) child = self.api.inherit('Child', parent, { 'extra': fields.String, }) self.api.model('Output', { 'child': fields.Nested(child), 'children': fields.List(fields.Nested(child)) }) self.assertIn('Person', self.api.models) self.assertIn('Child', self.api.models) def test_polymorph_inherit_common_ancestor(self): class Child1: pass class Child2: pass parent = self.api.model('Person', { 'name': fields.String, 'age': fields.Integer, }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) mapping = { Child1: child1, Child2: child2, } output = self.api.model('Output', { 'child': fields.Polymorph(mapping) }) # Should use the common ancestor self.assertEqual(output.__schema__, { 'properties': { 'child': {'$ref': '#/definitions/Person'}, } })
ns = api.namespace('todos', description='TODO operations') TODOS = { 'todo1': { 'task': 'build an API' }, 'todo2': { 'task': '?????' }, 'todo3': { 'task': 'profit!' }, } todo = api.model( 'Todo', {'task': fields.String(required=True, description='The task details')}) listed_todo = api.model( 'ListedTodo', { 'id': fields.String(required=True, description='The todo ID'), 'todo': fields.Nested(todo, description='The Todo') }) def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: api.abort(404, "Todo {} doesn't exist".format(todo_id)) parser = api.parser()
address_parser = api.parser() address_parser.add_argument("q", required=True, dest='q', location='args', help='Query') IRIS_MODEL = OrderedDict([('iris', fields.String), ('city', fields.String), ('citycode', fields.String), ('name', fields.String), ('complete_code', fields.String), ('type', fields.String)]) ADDRESS_MODEL = IRIS_MODEL.copy() ADDRESS_MODEL["address"] = fields.String ADDRESS_MODEL["lon"] = fields.Float ADDRESS_MODEL["lat"] = fields.Float iris_fields = api.model('Iris', IRIS_MODEL) address_fields = api.model('Address', ADDRESS_MODEL) @service.route('/doc/') def swagger_ui(): return apidoc.ui_for(api) @api.route("/iris/<string:code>") class IrisCode(Resource): @api.doc(parser=iris_code_parser, description="get data for a specific IRIS (four digits)") @api.marshal_with(iris_fields, envelope='iris') def get(self, code): args = iris_code_parser.parse_args()
app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api( app, version='1.0', title='TodoMVC API', description='A simple TodoMVC API', ) ns = api.namespace('todos', description='TODO operations') todo = api.model( 'Todo', { 'id': fields.Integer(readOnly=True, description='The task unique identifier'), 'task': fields.String(required=True, description='The task details') }) class TodoDAO(object): def __init__(self): self.counter = 0 self.todos = [] def get(self, id): for todo in self.todos: if todo['id'] == id: return todo api.abort(404, "Todo {} doesn't exist".format(id))
def test_nested_field(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) prop = utils.field_to_property(fields.Nested(nested_fields)) self.assertEqual(prop, {'$ref': 'NestedModel', 'required': True})
class SwaggerFieldsTestCase(TestCase): def setUp(self): super(SwaggerFieldsTestCase, self).setUp() blueprint = Blueprint('api', __name__) self.api = Api(blueprint) self.app.register_blueprint(blueprint) def test_classname_field(self): model = self.api.model('Test', { 'name': fields.ClassName(), }) class FakeClass(object): pass data = self.api.marshal(FakeClass(), model) self.assertEqual(data, {'name': 'FakeClass'}) def test_classname_field_dash(self): model = self.api.model('Test', { 'name': fields.ClassName(dash=True), }) class FakeClass(object): pass data = self.api.marshal(FakeClass(), model) self.assertEqual(data, {'name': 'fake_class'}) def test_polymorph_field(self): parent = self.api.model('Person', { 'name': fields.String, }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) class Child1(object): name = 'child1' extra1 = 'extra1' class Child2(object): name = 'child2' extra2 = 'extra2' mapping = {Child1: child1, Child2: child2} thing = self.api.model('Thing', { 'owner': fields.Polymorph(mapping), }) def data(cls): return self.api.marshal({'owner': cls()}, thing) self.assertEqual(data(Child1), {'owner': { 'name': 'child1', 'extra1': 'extra1' }}) self.assertEqual(data(Child2), {'owner': { 'name': 'child2', 'extra2': 'extra2' }}) def test_polymorph_field_no_common_ancestor(self): child1 = self.api.model('Child1', { 'extra1': fields.String, }) child2 = self.api.model('Child2', { 'extra2': fields.String, }) class Child1(object): pass class Child2(object): pass mapping = {Child1: child1, Child2: child2} with self.assertRaises(ValueError): fields.Polymorph(mapping) def test_polymorph_field_unknown_class(self): parent = self.api.model('Person', { 'name': fields.String, }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) class Child1(object): name = 'child1' extra1 = 'extra1' class Child2(object): name = 'child2' extra2 = 'extra2' mapping = {Child1: child1, Child2: child2} thing = self.api.model('Thing', { 'owner': fields.Polymorph(mapping), }) with self.assertRaises(ValueError): self.api.marshal({'owner': object()}, thing) def test_polymorph_field_ambiguous_mapping(self): parent = self.api.model('Parent', { 'name': fields.String, }) child = self.api.inherit('Child', parent, { 'extra': fields.String, }) class Parent(object): name = 'parent' class Child(Parent): extra = 'extra' mapping = {Parent: parent, Child: child} thing = self.api.model('Thing', { 'owner': fields.Polymorph(mapping), }) with self.assertRaises(ValueError): self.api.marshal({'owner': Child()}, thing) def test_polymorph_field_required_default(self): parent = self.api.model('Person', { 'name': fields.String, }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) class Child1(object): name = 'child1' extra1 = 'extra1' class Child2(object): name = 'child2' extra2 = 'extra2' mapping = {Child1: child1, Child2: child2} thing = self.api.model( 'Thing', { 'owner': fields.Polymorph( mapping, required=True, default={'name': 'default'}), }) data = self.api.marshal({}, thing) self.assertEqual(data, {'owner': {'name': 'default'}}) def test_polymorph_field_not_required(self): parent = self.api.model('Person', { 'name': fields.String, }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) class Child1(object): name = 'child1' extra1 = 'extra1' class Child2(object): name = 'child2' extra2 = 'extra2' mapping = {Child1: child1, Child2: child2} thing = self.api.model('Thing', { 'owner': fields.Polymorph(mapping), }) data = self.api.marshal({}, thing) self.assertEqual(data, {'owner': None}) def test_discriminator_field(self): model = self.api.model('Test', { 'name': fields.String(discriminator=True), }) data = self.api.marshal(object(), model) self.assertEqual(data, {'name': 'Test'}) def test_multiple_discriminator_field(self): model = self.api.model( 'Test', { 'name': fields.String(discriminator=True), 'name2': fields.String(discriminator=True), }) with self.assertRaises(ValueError): self.api.marshal(object(), model) def test_polymorph_with_discriminator(self): parent = self.api.model('Person', { 'name': fields.String, 'model': fields.String(discriminator=True), }) child1 = self.api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = self.api.inherit('Child2', parent, { 'extra2': fields.String, }) class Child1(object): name = 'child1' extra1 = 'extra1' class Child2(object): name = 'child2' extra2 = 'extra2' mapping = {Child1: child1, Child2: child2} thing = self.api.model('Thing', { 'owner': fields.Polymorph(mapping), }) def data(cls): return self.api.marshal({'owner': cls()}, thing) self.assertEqual(data(Child1), { 'owner': { 'name': 'child1', 'model': 'Child1', 'extra1': 'extra1' } }) self.assertEqual(data(Child2), { 'owner': { 'name': 'child2', 'model': 'Child2', 'extra2': 'extra2' } })
from flask import Flask from flask.ext.restplus import Api, Resource, fields from pandas.core.frame import DataFrame from werkzeug.contrib.fixers import ProxyFix app = Flask(__name__) #app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app, version='1.0', title='TodoMVC API', description='A simple TodoMVC API', ) ns = api.namespace('todos', description='TODO operations') todo = api.model('Todo', { 'id': fields.Integer(readOnly=True, description='The task unique identifier'), 'task': fields.String(required=True, description='The task details') }) class TodoDAO(object): def __init__(self): self.counter = 0 self.todos = [] def get(self, id): for todo in self.todos: if todo['id'] == id: return todo api.abort(404, "Todo {} doesn't exist".format(id)) def create(self, data):
namespace = api.namespace("v1", description="v1") downloads = api.namespace("downloads", description="downloads") newPackArgs = api.parser() newPackArgs.add_argument("requestToken", location="form") newPackArgs.add_argument( "recipes", type=FileStorage, help="Tar archive that contains the recipes and related data following some rules.", location="files", ) packprocessInfo = {"status": fields.String, "description": fields.String, "percentage": fields.Integer} packprocessInfoModel = api.model("packprocessInfo", packprocessInfo) @namespace.route("/recipe") class PackageService(Resource): @api.doc(description="List packages (finished and under construction)") def get(self): list = checker.getList() return {"processes": list} @api.doc(description="Start to packetize recipe.", parser=newPackArgs) @api.response(201, "Created", packprocessInfoModel) def post(self): err, detail, res, recipes, code, package = None, None, {}, None, 200, None code = 200
api_v1 = Blueprint('api', __name__, url_prefix='/api/1') api = Api(api_v1, version='1.0', title='Todo API', description='A simple TODO API', ) ns = api.namespace('todos', description='TODO operations') TODOS = { 'todo1': {'task': 'build an API'}, 'todo2': {'task': '?????'}, 'todo3': {'task': 'profit!'}, } todo = api.model('Todo', { 'task': fields.String(required=True, description='The task details') }) listed_todo = api.model('ListedTodo', { 'id': fields.String(required=True, description='The todo ID'), 'todo': fields.Nested(todo, description='The Todo') }) def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: api.abort(404, "Todo {} doesn't exist".format(todo_id)) parser = api.parser() parser.add_argument('task', type=str, required=True, help='The task details', location='form')
from flask.ext.restplus import Api, Resource, fields app = Flask(__name__) api = Api(app, version='1.0', title='Resume Generator API', description='An API used to integrate resume information from various formats and transform them into different graphical representations.') ns = api.namespace('resumes', description='Resumes') resume_parser = api.parser() resume_parser.add_argument('username', type=str, required=True, help='Your username, used as an identifier for any request to the API', location='form') resume_parser.add_argument('fullname', type=str, required=True, help='Your full name', location='form') resume_parser.add_argument('age', type=int, required=True, help='Your age', location='form') resume = api.model('Resume', { 'username': fields.String(required=True), 'fullname': fields.String(required=True), 'age' : fields.Integer(required=True) }) SUPPORTED_INPUTS = ['json'] resume_content_parser = api.parser() resume_content_parser.add_argument('content', type=str, required=True, help='The resume content in the format described by content_type.', location='form') resume_content_parser.add_argument('content_type', type=str, required=True, help='The resume content type submitted. Currently supported: ' + ', '.join(SUPPORTED_INPUTS), location='form') resume_content = api.model('ResumeContent', { 'content' : fields.String(required=True), 'content_type' : fields.String(required=True, enum=SUPPORTED_INPUTS), }) SUPPORTED_VIEWS = ['kibana3']
from controllers.management import managementOps from datastore import dataStore from datastore.dataStore import DataStore app = Flask(__name__) api = Api( app, version='0.5', title='Docker commander API', description='An unified API to all Docker operations.', ) datastore = DataStore(app) # Common errorResponseModel = api.model('Error', generalSchemas.basic_error_response) def not_implemented(): result = { 'error': 'not_implemented', 'description': 'Feature not implemented yet' } return result, 500 def not_found(): result = {'error': 'not_found', 'description': 'Resource not found'} return result, 404
'NumberOfTime60-89DaysPastDueNotWorse', type=float, required=True, help='Number of mortgage and real estate loans including home equity lines of credit', location='form') parser.add_argument( 'NumberOfDependents', type=float, required=True, help='Number of mortgage and real estate loans including home equity lines of credit', location='form') resource_fields = api.model('Resource', { 'result': fields.String, }) from flask.ext.restplus import Resource @ns.route('/') class CreditApi(Resource): @api.doc(parser=parser) @api.marshal_with(resource_fields) def post(self): args = parser.parse_args() result = self.get_result(args) return result, 201 def get_result(self, args):
fields = api.model( 'Job', { 'id': fields.String(), 'name': fields.String(), 'task_class': fields.String(attribute=lambda x: x.func_ref.replace(':', '.').replace( '.execute', '')), 'next_run_time': fields.DateTime(dt_format='iso8601'), 'misfire_grace_time': fields.String(), 'coalesce': fields.Boolean(), 'trigger': fields.String(), 'args': fields.List(fields.String), 'start_date': fields.DateTime(attribute=lambda x: x.trigger.start_date, dt_format='iso8601'), 'end_date': fields.DateTime(attribute=lambda x: x.trigger.end_date, dt_format='iso8601'), 'timezone': fields.String(), 'year': fields.String(attribute=lambda x: x.trigger.fields[0] if not x.trigger.fields[0].is_default else None), 'month': fields.String(attribute=lambda x: x.trigger.fields[1] if not x.trigger.fields[1].is_default else None), 'day': fields.String(attribute=lambda x: x.trigger.fields[2] if not x.trigger.fields[2].is_default else None), 'week': fields.String(attribute=lambda x: x.trigger.fields[3] if not x.trigger.fields[3].is_default else None), 'day_of_week': fields.String(attribute=lambda x: x.trigger.fields[4] if not x.trigger.fields[4].is_default else None), 'hour': fields.String(attribute=lambda x: x.trigger.fields[5] if not x.trigger.fields[5].is_default else None), 'minute': fields.String(attribute=lambda x: x.trigger.fields[6] if not x.trigger.fields[6].is_default else None), 'second': fields.String(attribute=lambda x: x.trigger.fields[7] if not x.trigger.fields[7].is_default else None), })
def test_nested_field_with_description(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) prop = utils.field_to_property(fields.Nested(nested_fields, description='A description')) self.assertEqual(prop, {'$ref': 'NestedModel', 'required': True, 'description': 'A description'})
from flask import make_response, Flask from flask.ext.restplus import Api, Resource, fields def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({"response": data}), code) resp.headers.extend(headers or {}) return resp app = Flask(__name__) api = Api(app, default_mediatype="application/xml") api.representations["application/xml"] = output_xml hello_fields = api.model("Hello", {"entry": fields.String}) @api.route("/<string:entry>") class Hello(Resource): """ # you need requests >>> from requests import get >>> get('http://localhost:5000/me').content # default_mediatype '<?xml version="1.0" ?><response><hello>me</hello></response>' >>> get('http://localhost:5000/me', headers={"accept":"application/json"}).content '{"hello": "me"}' >>> get('http://localhost:5000/me', headers={"accept":"application/xml"}).content '<?xml version="1.0" ?><response><hello>me</hello></response>' """
address_parser = api.parser() address_parser.add_argument("q", required=True, dest='q', location='args', help='Query') IRIS_MODEL = OrderedDict([('iris', fields.String), ('city', fields.String), ('citycode', fields.String), ('name', fields.String), ('complete_code', fields.String), ('type', fields.String)]) ADDRESS_MODEL = IRIS_MODEL.copy() ADDRESS_MODEL["address"] = fields.String ADDRESS_MODEL["lon"] = fields.Float ADDRESS_MODEL["lat"] = fields.Float iris_fields = api.model('Iris', IRIS_MODEL) address_fields = api.model('Address', ADDRESS_MODEL) @service.route('/doc/', endpoint='doc') def swagger_ui(): return apidoc.ui_for(api) @api.route("/iris/<string:code>") class IrisCode(Resource): @api.doc(parser=iris_code_parser, description="get data for a specific IRIS (four digits)") @api.marshal_with(iris_fields, envelope='iris') def get(self, code): args = iris_code_parser.parse_args()
from models import Responses from tools import initializator from controllers import Installator, Check, Deploy, ControllerError app = Flask(__name__) api = Api( app, version='1', title='comcloud-node-agent', description='An unified API to all Docker operations.', ) ## Response models generalResponseModel = api.model('General', Responses.error) statusResponseModel = api.model('Status', Responses.error) errorResponseModel = api.model('Error', Responses.error) # Common def not_implemented(): result = { 'error': 'not_implemented', 'description': 'Feature not implemented yet' } return result, 500 def not_found():
from flask import Flask, request from flask.ext.restplus import Api, apidoc, Resource, reqparse, fields from werkzeug.datastructures import FileStorage from models import Responses from tools import initializator from controllers import Installator, Check, Deploy, ControllerError app = Flask(__name__) api = Api(app, version='1', title='comcloud-node-agent', description='An unified API to all Docker operations.',) ## Response models generalResponseModel = api.model('General', Responses.error) statusResponseModel = api.model('Status', Responses.error) errorResponseModel = api.model('Error', Responses.error) # Common def not_implemented(): result = {'error':'not_implemented', 'description':'Feature not implemented yet'} return result, 500 def not_found(): result = {'error':'not_found', 'description':'Resource not found'} return result, 404 def process_error(text): result = {'error':'process_error', 'description':'Error while processing request.'}
# PATH NAAR SWAGGER (/<NAMESPACE>/swagger) @blueprint.route('/sensoren/swagger/', endpoint='swagger') def swagger_ui(): return apidoc.ui_for(api) # EFFECTIEVE API GEDEELTE # => http://<SERVERNAME>/URL_PREFIX/<NAMESPACE>/ @ns.route('/', endpoint='sensoren') @api.doc(description='test') class MyResource(Resource): def get(self): return "Hello!" model = api.model('Model', { 'temperatuur': fields.String, }) # => http://<SERVERNAME>/URL_PREFIX/<NAMESPACE>/<ID> @ns.route('/<id>', endpoint='sensoren-id') @api.doc(params={'id': '1=koelcel - 2=diepvriescel'}) class dagklapperDag(Resource): @api.doc(description='Returns temperature') @api.response(200, 'Success', model) def get(self, id): return id if __name__ == '__main__': app.register_blueprint(blueprint) app.run(host='127.0.0.1', debug='on', port=5003)
address_parser.add_argument("q", required=True, dest='q', location='args', help='Query') IRIS_MODEL = OrderedDict([('iris', fields.String), ('city', fields.String), ('citycode', fields.String), ('name', fields.String), ('complete_code', fields.String), ('type', fields.String)]) COORD_MODEL = IRIS_MODEL.copy() COORD_MODEL["lon"] = fields.Float COORD_MODEL["lat"] = fields.Float ADDRESS_MODEL = COORD_MODEL.copy() ADDRESS_MODEL["address"] = fields.String iris_fields = api.model('Iris', IRIS_MODEL) coord_fields = api.model('Coord', COORD_MODEL) address_fields = api.model('Address', ADDRESS_MODEL) @service.route('/doc/') def swagger_ui(): return apidoc.ui_for(api) @api.route("/iris/<string:code>") class IrisCode(Resource): @api.doc(parser=iris_code_parser, description="get data for a specific IRIS (four digits)") @api.marshal_with(iris_fields, envelope='iris') def get(self, code):
def test_with_readonly(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, readonly=True) self.assertEqual(field.__schema__, {'$ref': '#/definitions/NestedModel', 'readOnly': True})
from rested_users.user_dao import UserDAO from rested_users.exceptions import GroupError, UserError app = Flask(__name__) app.wsgi_app = ProxyFix(app.wsgi_app) api = Api(app, version=VERSION, title=TITLE, description=DESCRIPTION, ) group_ns = api.namespace('groups', description='Group operations') user_ns = api.namespace('users', description='User operations') user = api.model('user', { 'first_name': fields.String(required=False, description='The firstname of the user.', default=""), 'last_name': fields.String(required=False, description='The lastname of the user.', default=""), 'userid': fields.String(required=True, description='The userid of the user.'), 'groups': fields.List(fields.String, required=False, description='A list of groups the user belongs to.', default=[""]) }) group = api.model('group', { 'name': fields.String(required=True, description='The name of the group.') }) group_update = api.model('group_update', { 'members': fields.List(fields.String, required=True, description='Updated membership list for the specified group.') }) user_parser = api.parser() user_parser.add_argument('first_name', type=str, required=False, help='The firstname of the user.') user_parser.add_argument('last_name', required=False, help='The lastname of the user.')
def test_nullable_nested_field(self): api = Api(self.app) nested_fields = api.model('NestedModel', {'name': fields.String}) prop = utils.field_to_property(fields.Nested(nested_fields, allow_null=True)) self.assertEqual(prop, {'$ref': 'NestedModel'})
_here = osp.dirname(osp.abspath(__file__)) DBFILE = osp.join("data", "music.db") LOG_FORMAT = "%(asctime)s :: %(levelname)s :: %(module)s :: %(message)s" logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) Logger = logging.getLogger(__name__) app = Flask(__name__) api = Api(app, title="Music Collection", version='0.1', description="Retrieve data from your music collection") MODEL = api.model("CD", {"artist": fields.String, "album": fields.String, "year": fields.Integer, "genre": fields.String, "label": fields.String, "uri": fields.Url("album_resource", absolute=True)}) def _query(q, *params): with sqlite3.connect(DBFILE) as cnx: cu = cnx.cursor() cu.execute(q, params) columns = [x[0] for x in cu.description] # replace 'id' by 'album_id' columns[columns.index('id')] = 'album_id' return [dict(zip(columns, x)) for x in cu.fetchall()] def search_artist(name, limit=None):
from flask import Flask from flask.ext.restplus import Api, Resource, fields app = Flask(__name__) api = Api( app, version="1.0", title="Todo API", description="A simple TODO API extracted from the original flask-restful example", ) ns = api.namespace("todos", description="TODO operations") TODOS = {"todo1": {"task": "build an API"}, "todo2": {"task": "?????"}, "todo3": {"task": "profit!"}} todo = api.model("Todo", {"task": fields.String(required=True, description="The task details")}) listed_todo = api.model( "ListedTodo", { "id": fields.String(required=True, description="The todo ID"), "todo": fields.Nested(todo, description="The Todo"), }, ) def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: api.abort(404, "Todo {} doesn't exist".format(todo_id))
from flask import make_response, Flask from flask.ext.restplus import Api, Resource, fields def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response': data}), code) resp.headers.extend(headers or {}) return resp app = Flask(__name__) api = Api(app, default_mediatype='application/xml') api.representations['application/xml'] = output_xml hello_fields = api.model('Hello', {'entry': fields.String}) @api.route('/<string:entry>') class Hello(Resource): """ # you need requests >>> from requests import get >>> get('http://*****:*****@api.doc(model=hello_fields, params={'entry': 'The entry to wrap'})