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_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_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_will_prettyprint_json_in_debug_mode(self): self.app.config['DEBUG'] = True api = Api(self.app) class Foo1(Resource): def get(self): return {'foo': 'bar', 'baz': 'asdf'} api.add_resource(Foo1, '/foo', endpoint='bar') with self.app.test_client() as client: foo = client.get('/foo') # Python's dictionaries have random order (as of "new" Pythons, # anyway), so we can't verify the actual output here. We just # assert that they're properly prettyprinted. lines = foo.data.splitlines() lines = [line.decode() for line in lines] self.assertEquals("{", lines[0]) self.assertTrue(lines[1].startswith(' ')) self.assertTrue(lines[2].startswith(' ')) self.assertEquals("}", lines[3]) # Assert our trailing newline. self.assertTrue(foo.data.endswith(b'\n'))
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_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_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_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_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_json_float_marshalled(self): api = Api(self.app) class FooResource(Resource): fields = {'foo': fields.Float} def get(self): return marshal({"foo": 3.0}, self.fields) api.add_resource(FooResource, '/api') app = self.app.test_client() resp = app.get('/api') self.assertEquals(resp.status_code, 200) self.assertEquals(resp.data.decode('utf-8'), '{"foo": 3.0}\n')
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)
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'})
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 setUp(self): super(SwaggerFieldsTestCase, self).setUp() blueprint = Blueprint('api', __name__) self.api = Api(blueprint) self.app.register_blueprint(blueprint)
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 Flask from flask.ext.restplus import Api from flask.ext.restplus import fields from sklearn.externals import joblib app = Flask(__name__) api = Api( app, version='1.0', title='Credit API', description='A simple Prediction API') ns = api.namespace('approve_credit', description='Approve Credit Operations')
def setUp(self): super(ModelTestCase, self).setUp() blueprint = Blueprint('api', __name__) self.api = Api(blueprint) self.app.register_blueprint(blueprint)
from .attendees import api as attendees_api from .tickets import api as tickets_apt from helpers.error_docs import api as error_models from helpers.errors import ( NotFoundError, NotAuthorizedError, PermissionDeniedError, ValidationError, InvalidServiceError, ServerError, ) api_v2 = Blueprint('api', __name__, url_prefix='/api/v2') api = Api(api_v2, version='2.0', title='Organizer Server APIs', description='Open Event Organizer APIs') api.add_namespace(event_api) api.add_namespace(session_api) api.add_namespace(track_api) api.add_namespace(speaker_api) api.add_namespace(sponsor_api) api.add_namespace(microlocation_api) api.add_namespace(login_api) api.add_namespace(exports_api) api.add_namespace(imports_api) api.add_namespace(users_api) api.add_namespace(extras_api) api.add_namespace(notifications_api) api.add_namespace(error_models)
from flask import Flask, request from flask.ext.restplus import Api, apidoc, Resource, reqparse, fields, marshal_with from schemas import builderSchemas, clusterSchemas, composerSchemas, generalSchemas from werkzeug.datastructures import FileStorage 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
from flask import Flask from flask.ext.restplus import Api app = Flask("dmon-logstash") app.config['RESTPLUS_VALIDATE'] = True api = Api( app, version='0.0.2', title='DICE Monitoring Logstash API', description= "RESTful API for the DICE Monitoring Platform Logstash agent (dmon-logstash)", ) # changes the descriptor on the Swagger WUI and appends to api /dmon and then /v1 agent = api.namespace('agent', description='dmon logstash operations')
from flask import Flask from flask.ext.restplus import Api, Resource, fields _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]
from flask import Flask from flask.ext.restplus import Api, Resource, fields 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):
from flask import Flask from flask.ext.restplus import Api from flask.ext.restplus import fields from sklearn.externals import joblib app = Flask(__name__) api = Api(app, version='1.0', title='Credit API', description='A simple Prediction API') ns = api.namespace('approve_credit', description='Approve Credit Operations') parser = api.parser() parser.add_argument( 'RevolvingUtilizationOfUnsecuredLines', type=float, required=True, help= 'Total balance on credit cards and personal lines of credit except real estate and no installment debt like car loans divided by the sum of credit limits', location='form') parser.add_argument('age', type=float, required=True, help='Age of borrower in years', location='form') parser.add_argument( 'NumberOfTime30-59DaysPastDueNotWorse', type=float, required=True,
import os, sys, json, requests, traceback from datetime import datetime from flask import Blueprint, request, redirect, url_for, Response, current_app from flask.ext.restplus import Api, apidoc, Resource, fields from flask.ext.login import login_user, logout_user, login_required from fv_prov_es import cache from fv_prov_es.lib.utils import get_prov_es_json, get_ttl from fv_prov_es.lib.import_utils import get_es_conn, import_prov NAMESPACE = "prov_es" services = Blueprint('api_v0-2', __name__, url_prefix='/api/v0.2') api = Api( services, ui=False, version="0.2", title="PROV-ES API", description="API for ingest, query, and visualization of PROV-ES documents" ) ns = api.namespace(NAMESPACE, description="PROV-ES operations") @services.route('/doc/', endpoint='doc') def swagger_ui(): return apidoc.ui_for(api)
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))
import os, sys, json, requests, traceback from datetime import datetime from flask import Blueprint, request, redirect, url_for, Response, current_app from flask.ext.restplus import Api, apidoc, Resource, fields from flask.ext.login import login_user, logout_user, login_required from fv_prov_es import cache from fv_prov_es.lib.utils import get_prov_es_json, get_ttl from fv_prov_es.lib.import_utils import get_es_conn, import_prov NAMESPACE = "prov_es" services = Blueprint('api_v0-1', __name__, url_prefix='/api/v0.1') api = Api(services, ui=False, version="0.1", title="PROV-ES API", description="API for ingest, query, and visualization of PROV-ES documents") ns = api.namespace(NAMESPACE, description="PROV-ES operations") @services.route('/doc/', endpoint='doc') def swagger_ui(): return apidoc.ui_for(api) @ns.route('/query', endpoint='query') @api.doc(responses={ 200: "Success", 400: "Invalid parameters", 500: "Query execution failed" }, description="Query PROV-ES ElasticSearch index and return results as a JSONP response.") class Query(Resource): """Query ElasticSearch index and return results as a JSONP response."""
from .imports import api as imports_api from .users import api as users_api from helpers.error_docs import api as error_models from helpers.errors import ( NotFoundError, NotAuthorizedError, PermissionDeniedError, ValidationError, InvalidServiceError, ServerError, ) api_v2 = Blueprint('api', __name__, url_prefix='/api/v2') api = Api(api_v2, version='2.0', title='Organizer Server APIs', description='Open Event Organizer APIs') api.add_namespace(event_api) api.add_namespace(session_api) api.add_namespace(track_api) api.add_namespace(speaker_api) api.add_namespace(sponsor_api) api.add_namespace(microlocation_api) api.add_namespace(login_api) api.add_namespace(exports_api) api.add_namespace(imports_api) api.add_namespace(users_api) api.add_namespace(error_models)
""" Initialize Flask app """ from flask import Flask, g from flask.ext.restplus import Api from config import config app = Flask('application') api = Api(app, catch_all_404s=True, title='Rest Engine API', description='A simple API running on Google App Engine') from app.user.resources import * from app.user.models import User token_parser = api.parser() token_parser.add_argument( 'X-Session-Token', type=str, location='headers' ) @app.before_request def current_user(): args = token_parser.parse_args() token = args['X-Session-Token'] valid, data = User.verify_session_token(token) g.user = None if valid: if not data.get('password_reset'): g.user = User.get_by_id(data.get('user_id'))
from flask import Flask from flask.ext.restplus import Api app = Flask("dmon-adp") api = Api(app, version='0.0.1', title='DICE Anomaly Detection Platform API', description="RESTful API for the DICE Anomaly Detection Platform (dmon-adp)", ) # changes the descriptor on the Swagger WUI and appends to api /dmon and then /v1 adp = api.namespace('adp', description='dmon anomaly detection operations')
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'}, } })
Logger = logging.getLogger(__name__) service = Blueprint( 'api', __name__) @service.route('/') def index(): return render_template("index.html") api = Api(service, title='INSEE/IRIS Geolocalizer', ui=False, version='0.1', description="Retrieve some data related to the IRIS codes. Look for an IRIS from an address.") iris_code_parser = api.parser() iris_code_parser.add_argument("limit", required=False, default=10, dest='limit', location='args', help='Limit') 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),
import settings from settings import GENERAL_DEBUG 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'
#!/usr/bin/env python from flask import Flask, Blueprint from flask.ext.restplus import Api app = Flask(__name__) app.config[ 'RESTPLUS_MASK_SWAGGER'] = False #Disables fields masks, http://flask-restplus.readthedocs.org/en/stable/mask.html app.config[ 'SWAGGER_UI_DOC_EXPANSION'] = 'list' #Intitial documentation expansion state (none, list or full), http://flask-restplus.readthedocs.org/en/stable/swaggerui.html blueprint = Blueprint('api', __name__, url_prefix='/api') #Disable documentation UI with "doc=False" api = Api(blueprint, version='1.0', title='Vekarus API', description='', doc='/') app.register_blueprint(blueprint) import status
# -*- coding: utf-8 -*- from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.restplus import Api db = SQLAlchemy() api = Api(version='1.0', title='Gastos Abertos', description='API para acesso a dados orçamentários', default='/api/v1')
from flask.ext.restplus import Api, Resource, fields from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR from tasks import BaseTask, recorder, example import atexit app = Flask(__name__) app.config.SWAGGER_UI_DOC_EXPANSION = 'list' blueprint = Blueprint('api', __name__, url_prefix='/api') api = Api(blueprint, version='1.0', title="APScheduler API", description="A simple API to access APScheduler.") app.register_blueprint(blueprint) ns = api.namespace('jobs', description='Job operations') # Fields that are expected and need to be exposed from a Job fields = api.model( 'Job', { 'id': fields.String(), 'name': fields.String(), 'task_class': fields.String(attribute=lambda x: x.func_ref.replace(':', '.').replace( '.execute', '')),
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' } })
import settings from flask import Flask, request from flask.ext.restplus import Api, apidoc, Resource, reqparse, fields, marshal_with from schemas import builderSchemas, clusterSchemas, composerSchemas, generalSchemas from werkzeug.datastructures import FileStorage 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
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})
def setup_logging(app): log_file_path = app.config.get('LOG_FILE') log_level = app.config.get('LOG_LEVEL', logging.WARN) if log_file_path: # pragma: no cover file_handler = RotatingFileHandler(log_file_path) file_handler.setFormatter(Formatter( '%(name)s:%(levelname)s:[%(asctime)s] %(message)s ' '[in %(pathname)s:%(lineno)d]' )) file_handler.setLevel(log_level) app.logger.addHandler(file_handler) logger = logging.getLogger('sun4allmobile') logger.setLevel(log_level) logger.addHandler(file_handler) def setup_db(app): app.db = SQLAlchemy(app) app=create_app() api=Api( app, version='1.0', title='Todo API', description='A simple TODO API extracted from the original flask-restful example', default='api_socientize', default_label='Socientize Swagger', contact='*****@*****.**' ) db=app.db
from app import app from flask import Flask from flask.ext.restplus import Api, Resource, fields api = Api( app, version="1.0", title="TrueCar API", description="A simple TrueCar API borrowed from flask-restful example!" ) ns = api.namespace("vsnLookup", description="TrueCar API") # todo: not now probably continue later
import hysds_commons.container_utils import hysds_commons.hysds_io_utils import hysds_commons.job_spec_utils import hysds_commons.job_utils from hysds.log_utils import log_custom_event from mozart import app #Library backend imports import mozart.lib.job_utils import mozart.lib.queue_utils services = Blueprint('api_v0-2', __name__, url_prefix='/api/v0.2') api = Api(services, ui=False, version="0.2", title="Mozart API", description="API for HySDS job submission and query.") #Namespace declarations QUEUE_NS = "queue" queue_ns = api.namespace(QUEUE_NS, description="Mozart queue operations") JOBSPEC_NS = "job_spec" job_spec_ns = api.namespace(JOBSPEC_NS, description="Mozart job-specification operations") JOB_NS = "job" job_ns = api.namespace(JOB_NS, description="Mozart job operations") CONTAINER_NS = "container" container_ns = api.namespace(CONTAINER_NS, description="Mozart container operations")
from flask import Flask, Blueprint from flask.ext.restplus import Api, Resource, fields 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))
from flask import Flask from flask.ext.restplus import Api app = Flask("dmon-agent") api = Api(app, version='0.0.4', title='DICE Monitoring Agent API', description="RESTful API for the DICE Monitoring Platform Agent (dmon-agent)", ) # changes the descriptor on the Swagger WUI and appends to api /dmon and then /v1 agent = api.namespace('agent', description='dmon agent operations')
'message': "This field can't be empty.", 'status': 401, }, 'ValidationError': { 'message': "This field can't be empty.", 'status': 402, }, 'RestException': { 'message': "This field can't be empty.", 'status': 400, } } api = Api(app, version='1.0', title='API', description='Api para el tp de arquitectura', errors=errors) #@api.errorhandler(Exception) #def handle_custom_exception(error): # return {'message': 'What you want'}, 400 ed = EventDocument(api) EventDC = ed.event ErrorDC = ed.error PaginateEventsDC = ed.paginateEvents EventsDC = ed.events
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(