def test_list_fields_with_nested_inherited(self): api = Api(self.app) person = api.model('Person', { 'name': fields.String, 'age': fields.Integer }) child = api.inherit('Child', person, { 'attr': fields.String }) family = api.model('Family', { 'children': fields.List(fields.Nested(child)) }) result = mask.apply(family.resolved, 'children{name,attr}') data = {'children': [ {'name': 'John', 'age': 5, 'attr': 'value-john'}, {'name': 'Jane', 'age': 42, 'attr': 'value-jane'}, ]} expected = {'children': [ {'name': 'John', 'attr': 'value-john'}, {'name': 'Jane', 'attr': 'value-jane'}, ]} self.assertDataEqual(marshal(data, result), expected) # Should leave th original mask untouched self.assertDataEqual(marshal(data, family), data)
def test_marshal_with_handle_polymorph(self, app, client): api = Api(app) parent = api.model('Person', { 'name': fields.String, }) child1 = api.inherit('Child1', parent, { 'extra1': fields.String, }) child2 = 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 = api.model('Thing', { 'owner': fields.Polymorph(mapping), }) @api.route('/thing-1/') class Thing1Resource(Resource): @api.marshal_with(thing) def get(self): return {'owner': Child1()} @api.route('/thing-2/') class Thing2Resource(Resource): @api.marshal_with(thing) def get(self): return {'owner': Child2()} data = client.get_json('/thing-1/', headers={'X-Fields': 'owner{name}'}) assert data == {'owner': {'name': 'child1'}} data = client.get_json('/thing-1/', headers={'X-Fields': 'owner{extra1}'}) assert data == {'owner': {'extra1': 'extra1'}} data = client.get_json('/thing-2/', headers={'X-Fields': 'owner{name}'}) assert data == {'owner': {'name': 'child2'}}
def test_marshal_with_expose_mask_header(self, app, client): api = Api(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 = client.get_specs() op = specs['paths']['/test/']['get'] assert 'parameters' in op assert len(op['parameters']) == 1 param = op['parameters'][0] assert param['name'] == 'X-Fields' assert param['type'] == 'string' assert param['format'] == 'mask' assert param['in'] == 'header' assert 'required' not in param assert 'default' not in param
def test_marshal_with_expose_custom_mask_header(self, app, client): api = Api(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 } app.config['RESTPLUS_MASK_HEADER'] = 'X-Mask' specs = client.get_specs() op = specs['paths']['/test/']['get'] assert 'parameters' in op assert len(op['parameters']) == 1 param = op['parameters'][0] assert param['name'] == 'X-Mask'
def test_marshal_with_disabling_mask_header(self, app, client): api = Api(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 } app.config['RESTPLUS_MASK_SWAGGER'] = False specs = client.get_specs() op = specs['paths']['/test/']['get'] assert 'parameters' not in 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_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_honour_header_field_mask_with_default_mask_and_default_model_mask(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }, mask='{name,boolean}') @api.route('/test/') class TestResource(Resource): @api.marshal_with(model, mask='{name,age}') def get(self): return { 'name': 'John Doe', 'age': 42, 'boolean': True } data = self.get_json('/test/', headers={ 'X-Fields': '{name}' }) self.assertEqual(data, { 'name': 'John Doe', })
def test_marshal_with_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): @api.marshal_with(model) def get(self): return { 'name': 'John Doe', 'age': 42, 'boolean': True } 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('Person', { '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_handle_inheritance(self): api = Api(self.app) person = api.model('Person', { 'name': fields.String, 'age': fields.Integer, }) child = api.inherit('Child', person, { 'extra': fields.String, }) data = { 'name': 'John Doe', 'age': 42, 'extra': 'extra' } values = ( ('name', {'name': 'John Doe'}), ('name,extra', {'name': 'John Doe', 'extra': 'extra'}), ('extra', {'extra': 'extra'}), ) for mask, expected in values: result = marshal(data, child, mask=mask) self.assertEqual(result, expected)
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) self.assertNotIn('default', param)
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_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(parser_to_params(parser), {"todo": {"type": "Todo", "in": "body"}})
def test_marshal_with_honour_complex_field_mask_header(self): api = Api(self.app) person = api.model('Person', person_fields) child = api.inherit('Child', person, { 'attr': fields.String }) family = api.model('Family', { 'father': fields.Nested(person), 'mother': fields.Nested(person), 'children': fields.List(fields.Nested(child)), 'free': fields.List(fields.Raw), }) house = api.model('House', { 'family': fields.Nested(family, attribute='people') }) @api.route('/test/') class TestResource(Resource): @api.marshal_with(house) def get(self): return {'people': { 'father': {'name': 'John', 'age': 42}, 'mother': {'name': 'Jane', 'age': 42}, 'children': [ {'name': 'Jack', 'age': 5, 'attr': 'value-1'}, {'name': 'Julie', 'age': 7, 'attr': 'value-2'}, ], 'free': [ {'key-1': '1-1', 'key-2': '1-2'}, {'key-1': '2-1', 'key-2': '2-2'}, ] }} data = self.get_json('/test/', headers={ 'X-Fields': 'family{father{name},mother{age},children{name,attr},free{key-2}}' }) expected = {'family': { 'father': {'name': 'John'}, 'mother': {'age': 42}, 'children': [{'name': 'Jack', 'attr': 'value-1'}, {'name': 'Julie', 'attr': 'value-2'}], 'free': [{'key-2': '1-2'}, {'key-2': '2-2'}] }} self.assertEqual(data, expected)
def test_with_readonly(self, app): api = Api(app) nested_fields = api.model('NestedModel', {'name': fields.String}) field = fields.Nested(nested_fields, readonly=True) assert field.__schema__ == { 'readOnly': True, 'allOf': [{'$ref': '#/definitions/NestedModel'}] }
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(parser_to_params(parser), { 'todo': { 'type': 'Todo', 'in': 'body', }, })
def test_raise_400_on_invalid_mask(self, app, client): api = Api(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 response = client.get('/test/', headers={'X-Fields': 'name{,missing}'}) assert response.status_code == 400 assert response.content_type == 'application/json'
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; charset=utf-8')
def test_marshal_with_skip_missing_fields(self, app, client): api = Api(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 = client.get_json('/test/', headers={'X-Fields': '{name,missing}'}) assert data == {'name': 'John Doe'}
def test_marshal_with_expose_default_model_mask_header(self, app, client): api = Api(app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }, mask='{name,age}') @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): pass specs = client.get_specs() definition = specs['definitions']['Test'] assert 'x-mask' in definition assert definition['x-mask'] == '{name,age}'
def test_marshal_with_expose_default_model_mask_header(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }, mask='{name,age}') @api.route('/test/') class TestResource(Resource): @api.marshal_with(model) def get(self): pass specs = self.get_specs() definition = specs['definitions']['Test'] self.assertIn('x-mask', definition) self.assertEqual(definition['x-mask'], '{name,age}')
def test_marshal_with_honour_header_default_mask_with_default_model_mask(self, app, client): api = Api(app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }, mask='{name,boolean}') @api.route('/test/') class TestResource(Resource): @api.marshal_with(model, mask='{name}') def get(self): return { 'name': 'John Doe', 'age': 42, 'boolean': True } data = client.get_json('/test/') assert data == {'name': 'John Doe'}
def test_marshal_honour_field_mask(self): api = Api(self.app) model = api.model('Test', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }) data = { 'name': 'John Doe', 'age': 42, 'boolean': True } result = api.marshal(data, model, mask='{name,age}') self.assertEqual(result, { 'name': 'John Doe', 'age': 42, })
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_honour_custom_field_mask(self, app, client): api = Api(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 } app.config['RESTPLUS_MASK_HEADER'] = 'X-Mask' data = client.get_json('/test/', headers={'X-Mask': '{name,age}'}) assert data == {'name': 'John Doe', 'age': 42}
def test_marshal_with_honour_field_mask_header(self, app, client): api = Api(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 } data = client.get_json('/test/', headers={ 'X-Fields': '{name,age}' }) assert data == {'name': 'John Doe', 'age': 42}
app = Flask(__name__) with app.app_context(): dbh = DbStore() print("Inside the app!") blueprint = Blueprint("api", __name__, url_prefix="/api") api = Api(blueprint, version="0.1.10", title="Nihongo flash cards API", description="A simple Rest API to serve related data") app.register_blueprint(blueprint) ns = api.namespace('flashcards', description="Operations related to flash cards") flashcards = api.model('Hello', { "question": fields.String(required=True, description="Write the front size of the card (in your native language)."), "answer": fields.String(required=True, description="Write the corresponding Nihongo translation at the back of this same card.") }) # parser = ns.parser() # parser.add_argument("flashcard", type=list, required=True, help="Write the front size of the card (in your native language).", location="json") # parser.add_argument("answer", type=str, required=True, help="Write the corresponding Nihongo translation at the back of this same card.", location="args") @app.route('/favicon.ico') def favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico') @app.route("/", methods=["GET", "POST"])
"type_func": fields.String, "default": "some msg~" }, "aeg": { "type_func": fields.Integer, "required": True }, } basic_model = api.model( "Basic_Model", { "name": fields.String(required=True, description="use error for demo error handler"), "gender": fields.String(enum=["male", "female"], required=True), "msg": fields.String(default="some msg~"), "aeg": fields.Integer(required=True), }, ) resp_fields = api.model( "Response_Fields", { "returnCode": fields.Integer(description="服務是否有正常執行,正常執行為 0"), "message": fields.String(description="回傳內容"), }, )
help='Year', location='args') parser.add_argument('Data title', type=str, required=True, help='title the movie', location='args') parser.add_argument('Data plot', type=str, required=True, help='Description about the movie', location='args') resource_fields = api.model('Resource', { 'result': fields.String, }) @ns.route('/') class PriceApi(Resource): @api.doc(parser=parser) @api.marshal_with(resource_fields) def get(self): args = parser.parse_args() return { "result": predict_movie_genre(args['Data Year'], args['Data title'], args['Data plot']) }, 200
# Define the model so that the docs reflect what can be sent product_model = api.model( 'Product', { 'id': fields.Integer(required=True, description='The id of the product'), 'name': fields.String(required=True, description='The name of the product'), 'description': fields.String(required=True, description='Detailed information about product'), 'category': fields.String(required=True, description='The category of product'), 'price': fields.Integer(required=True, description='The price of the product'), 'condition': fields.String(required=True, description='The condition of the product'), 'inventory': fields.Integer(required=True, description='The inventory of the product'), 'review': fields.String(required=False, description='The review of the product'), 'rating': fields.Integer(required=True, description='The rating of the product'), 'hitCount': fields.Integer(required=False, description='times product has been rated'), 'updatedDate': fields.String(required=False, description="updated date product") })
def get_api_state(): config = configparser.ConfigParser() config.read('config.ini') return config['airvisual']['state'] #@weather_space.route('/') #def index(): # return redirect("https://redbeard-consulting.fr", code=302) #@weather_space.route('/weather_city/<string:city>', methods=['GET']) #@weather_space.route('/weather_city') weather_space = app.namespace('weather', description='Get the weather') model = app.model('City model', {'city': fields.String(required=True, description="Name of the city", help="First upper case like Paris or Bordeaux")}) @weather_space.route('/<string:city>', methods=['GET']) class WeatherCityClass(Resource): @app.doc(responses={200: 'OK', 400: 'Invalid Argument', 500: 'Mapping Key Error'}, params={'city': 'Give the name of the city (ex: Chartres or Paris)'}) #@app.expect(model) def get(self, city='Chartres'): try: api_key = get_api_key() except KeyError as e: weather_space.abort(401, e.__doc__, status="Could not retrieve openweathermap token", statusCode="401")
import os from util.timeUtil import local_time os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="ChalkRobot9900-24e64d2180c4.json" app = Flask(__name__) api = Api(app) @api.route("/hi") class Hello(Resource): def get(self): return "hello world", 200 name_model = api.model('model', {'name': fields.String(required=True), 'password': fields.String}) @api.route("/webhook") class Webhook(Resource): def post(self): try: data = request.get_json(silent=True) print(data) course = None outline = None if "course" in data['queryResult']['parameters']: course = data['queryResult']['parameters']['course'] if len(course) > 0: course = "comp" + course if 'outline' in data['queryResult']['parameters']: outline = data['queryResult']['parameters']['outline']
elif name == 'all_text': return AllTextPageExtractor() else: return None list_selector_type = ['css', 'xpath'] sim_check_params = api.model( 'sim_check_params', { 'main_url': fields.String( default= 'http://edition.cnn.com/2015/11/29/europe/syria-turkey-russia-warplane/index.html' ), 'sub_urls': fields.String(default=[ "http://edition.cnn.com/2015/11/27/opinions/cagaptay-turkey-russia-tensions/index.html?iid=ob_lockedrail_topeditorial&iref=obinsite", "http://edition.cnn.com/videos/world/2015/11/28/turkey-russia-tension-dougherty-cnni-nr-lklv.cnn?iid=ob_lockedrail_topeditorial&iref=obinsite", "http://edition.cnn.com/2015/02/10/europe/ukraine-war-how-we-got-here/index.html", "http://edition.cnn.com/2015/11/19/asia/north-south-korea-talks/index.html" ]) }) sim_check_response = api.model( 'sim_check_response', { 'error': fields.String( default= 'False (boolean) if request successfully, else return error message (string)' ),
from flask import Flask, request from flask_restplus import Resource, Api, fields, inputs, reqparse app = Flask(__name__) api = Api(app, default="ClickView Video", title="ClickView Video API", # Documentation Title description="This is just a API for the purpose of a ClickView practical exam") # Documentation Description expectedVideoInformation = api.model( "video", { "name" : fields.String("Name of Video"), "duration" : fields.Integer("Video Length"), "description": fields.String("Descript of video"), "dateCreated": fields.DateTime(dt_format='rfc822'), "id" : fields.Integer("Date"), "thumbnail": fields.Url('todo_resource'), "folder": fields.String("Folder location"), "tags": fields.List(fields.String("Genres/Tags")) } ) @api.route('/videos') class Videos(Resource): @api.response(200, 'Successful') @api.doc(description="Gets all videos - This include all information associated with the video") def get(self): return db.getVideos(); @api.response(201, 'New Video has been created') @api.response(200, 'Video already exists')
flask_app = Flask(__name__) app = Api(flask_app, version='1.0', title='HACKATHON CNJ 1.0', description='HACKATHON CNJ 1.0 REST Service') ns = app.namespace('', description='HACKATHON CNJ 1.0 REST') historicoFase = app.model( 'historicoFase', { 'nome': fields.String(required=True, description='Nome da fase'), 'situacao': fields.String(required=True, description='Situacao da fase'), 'dataConclusao': fields.String(required=True, description='Data de conclusão da fase'), 'dataInicio': fields.String(required=True, description='Data de início da fase') }) dadoFase = app.model( 'dadosFase', { 'nome': fields.String(required=True, description='Nome da fase'), 'duracao': fields.String(required=True, description='Duração da fase'), 'duracaoPrevista': fields.String(required=True, description='Estimativa de duração'), 'status':
file_upload_model = api.parser() file_upload_model.add_argument('file', type=FileStorage, location='files', required=True) file_visualize_model = api.parser() file_visualize_model.add_argument('request_id', type=str, location='args') output_model = api.parser() output_model.add_argument('request_id', type=str, location='args') output_model.add_argument('method', type=str, location='args') output_model.add_argument('analytic_name', type=str, location='args') preprocess_model = api.model("preprocess_request", { 'request_id': fields.String, 'method': fields.String }) analytic_model = api.model( "analytic_request", { 'analytic_name': fields.String, 'request_id': fields.String, 'method': fields.String }) @api.route('/api/v1/fileupload') class upload_file(Resource): @api.expect(file_upload_model) def post(self): try:
from flask import Flask from flask_restplus import Api, Resource, fields from flask_restplus import fields app = Flask(__name__) api = Api( app, version='1.0', title='Mock SMS API', description='Nexmo Mock', ) sms_info = api.model( 'Send SMS', { 'api_key': fields.String(description='api key', required=True), 'api_secret': fields.String(description='api secret', required=True), 'from': fields.String(description='From text', required=True), 'text': fields.String(description='SMS text', required=True), 'to': fields.String(description='phone number', required=True), }) data = {} @api.route('/sms/json') class SendSms(Resource): @api.doc(responses={404: 'Email Not found or password not match'}, body=sms_info) def post(self): global data data[api.payload['to']] = api.payload
id_client = db.Column(db.String, primary_key=True) prediction_date = db.Column(db.String) model_label = db.Column(db.String) score_label_0 = db.Column(db.String) score_label_1 = db.Column(db.String) def __repr__(self): return (u'<{self.__class__,__name__}: {self.id}>'.format(self=self)) #swagger model for marshalling outputs model = api.model( 'store_predictions', { 'id_client': fields.String, 'model_label': fields.String, 'score_label_0': fields.String, 'score_label_1': fields.String }) model_2 = api.model( 'store_predictions', { 'model_label': fields.String, 'score_label_0': fields.String, 'score_label_1': fields.String }) ## output #completar
# Api definition. api = Api( app, version='1.0', title='Todo API', description='A simple Todo API', ) ns = api.namespace('todos', description='TODO operations') todo = api.model( 'Todo', { '_id': fields.String(readOnly=True, description='The task unique identifier'), 'task': fields.String(required=True, description='The task details'), 'status': fields.Boolean( required=True, default=False, description='The task Status') }) class TodoDAO(object): @property def todos(self): todos = mongo.db.todos todo_items = todos.find() output = [] for todo in todo_items: output.append(todo)
from flask_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 todo MVC API') ns = api.namespace('todos', description='TODO operations') todo = api.model( 'Todo', { 'id': fields.Integer(readOnly=True, description='The task unique identifier'), 'tasks': 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 in self.todos: if todo['id'] == id: return todo
from flask import Blueprint, request from flask_restplus import Api, Resource, fields from project import db from project.api.models import User users_blueprint = Blueprint("users", __name__) api = Api(users_blueprint) # new user = api.model( "User", { "id": fields.Integer(readOnly=True), "username": fields.String(required=True), "email": fields.String(required=True), "created_date": fields.DateTime, }, ) class UsersList(Resource): @api.expect(user, validate=True) def post(self): post_data = request.get_json() username = post_data.get("username") email = post_data.get("email") response_object = {} user = User.query.filter_by(email=email).first()
from flask_restplus import reqparse, Api, Resource, fields import json from flask import Flask, request, Response from datetime import datetime import requests app = Flask(__name__) api = Api(app) model_400 = api.model('ErrorResponse400', { 'message': fields.String, 'errors': fields.Raw }) model_500 = api.model('ErrorResponse400', { 'status': fields.Integer, 'message': fields.String }) def check_positive(value): ivalue = float(value) if ivalue <= 0: raise argparse.ArgumentTypeError("%s is not a positive value" % value) return ivalue def expiration_date(value): today_date = datetime.today().strftime("%Y-%m-%d")
ns = api.namespace('Operações: Nodo Pessoal', description='') todo = api.model( 'Todo', { 'id': fields.Integer(readOnly=True, description='Identificado único de cada nodo pessoal'), 'nome': fields.String(required=True, description='Nome do nodo pessoal'), 'pais': fields.String(required=True, description='The task details'), 'idade': fields.String(required=True, description='Idade'), 'genero': fields.String(required=True, description='Feminino e Masculino'), 'endereco': fields.String(required=True, description='Endereço'), 'e-mail': fields.String(required=True, description='E-mail'), 'dt_nascimento': fields.String(required=True, description='Data de Nascimento'), 'Lat': fields.String(required=True, description='Latitude'), 'Lon': fields.String(required=True, description='Longitude'), 'perfil': fields.String(required=True, description='Agente, Morador, Turista') }) class TodoDAO(object):
import json app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/check_user/parcial2_villegas/data.db' api = Api(app, version='1.0', title='API for check system variables', description='An API to check system variables such as free ram, cpu usage and free disk') ns = api.namespace('v1.0/checks', description='Operations related to check system variables') db.app = app db.init_app(app) db.create_all() thread = RegisterTimer(60) thread.start() model1 = api.model('checks',{ 'checks': fields.List(fields.String), }) @ns.route('/') class Check(Resource): @api.response(200, 'List of checks succesfully returned', model1) def get(self): ''' return the check that can be made by the user ''' ret = {} ret['data'] = ['cpu', 'ram', 'disk'] return ret; parser = api.parser() parser.add_argument('size', type=int, help='parameter for size history', location='query', )
from werkzeug.exceptions import BadRequest blueprint = Blueprint('api_v1', __name__) api = Api( blueprint, title='WordCount API', version='1.0', description='Wordcount number of times word appear (Letter case is taking into account)', doc="/doc/", default='Count', default_label='Counter endpoints' ) request_model = api.model('Request', { 'url': fields.String('http://www.virtusize.com', required=True, description='URL to search'), 'word': fields.String('fit', required=True, description='Word to search'), }) response_model = api.model('Response', { 'url': fields.String(required=True, description='URL to search'), 'word': fields.String(required=True, description='Word to search'), 'count': fields.Integer(required=True, description='Number or times word appear'), }) errors_model_400 = api.model('Error400', { 'message': fields.Raw(example = {"field":["Error description"]}) }) errors_model_404 = api.model('Error404', { 'message': fields.Raw(example = 'URL was not found') })
@api.route('/doc') class Docs(Resource): def get(self): return api.__schema__ client = MongoClient(os.getenv('MONGO_ADDR', 'localhost'), 27017) db = client.db operators = db.operators ns = api.namespace('operator', description='Operations related to operators') o_input = api.model('Input', { 'name': fields.String(required=True, description='Input name'), 'type': fields.String(required=True, description='Input type'), }) o_output = api.model('Output', { 'name': fields.String(required=True, description='Input name'), 'type': fields.String(required=True, description='Input type'), }) operator_model = api.model('Operator', { 'name': fields.String(required=True, description='Operator name'), 'image': fields.String(required=False, description='Name of the associated docker image'), 'description': fields.String(required=False, description='Description of the operator'), 'pub': fields.Boolean(required=False), 'inputs': fields.List(fields.Nested(o_input)), 'outputs': fields.List(fields.Nested(o_output)) })
def init_api_routes(app, session): if app: api = Api(app) words_api = api.namespace( 'words', description='Initialize Words (only 5 letter words allowed)') players_api = api.namespace('players', description='Operations on player') game_api = api.namespace('games', description='Operations on games') add_player = api.model('Player', {'username': fields.String}) add_word = api.model('Word', {'word': fields.String}) @words_api.route('/initialize') class Words(Resource): @words_api.response(201, 'Created') @words_api.response(400, 'Bad Request') @players_api.expect(add_word) def post(self): '''Loads the words to database''' data = request.json new_word = Word(word=data["word"]) if len(data['word']) != 5: return "Word should be exactly 5 characters long", 400 session.add(new_word) session.commit() return "Word Added successfully", 201 @players_api.route('') class CreatePlayer(Resource): @players_api.response(200, 'Success') @players_api.response(400, 'Bad Request') @players_api.expect(add_player) def post(self): '''Creates a player''' data = request.json username = data["username"] already_exists = session.query(Player).filter_by( username=username).first() if already_exists: return "Player with username already exists", 400 new_player = Player(username=username) session.add(new_player) session.commit() return session.query(Player).filter_by( username=username).first().serialize(), 200 @players_api.route('/<int:player_id>') class GetPlayer(Resource): @players_api.response(200, 'Success') @players_api.response(404, 'Not Found') @players_api.doc( params={'player_id': 'The player_id of the ' + 'player'}) def get(self, player_id): '''Gets a player''' player = session.query(Player).filter_by( player_id=player_id).first() if player: return player.serialize(), 200 return "Player Does not exist", 404 @players_api.route('/<int:player_id>/games/start') class CreateGame(Resource): @players_api.response(200, 'Success') @players_api.response(404, 'Not Found') @players_api.doc( params={'player_id': 'The player_id of the ' + 'player'}) def get(self, player_id): '''Creates a game for a player''' word_id = randint(1, 501) correct = "_" * 5 guessed = "" status = "new game" already_exists = session.query(Player).filter_by( player_id=player_id).first() if not already_exists: return "Player with username doesn't exist", 400 new_game = Game(player_id, word_id, correct, guessed, status) session.add(new_game) session.commit() return session.query(Game).filter_by( player_id=player_id, word_id=word_id).first().serialize(), 200 @players_api.route('/<int:player_id>/games') class AllGame(Resource): @players_api.response(200, 'Success') @players_api.doc( params={'player_id': 'The player_id of the ' + 'player'}) def get(self, player_id): '''shows all games for a player''' games = session.query(Game).filter_by(player_id=player_id) games = [game.serialize() for game in games] return games, 200 @game_api.route('/<int:game_id>/guess/<string:guess>') class GuessGame(Resource): @game_api.response(200, 'Success') @game_api.response(404, 'Not Found') @game_api.response(400, 'Bad Request') @game_api.doc( params={ 'game_id': 'The game_id of the game', 'guess': 'The guess of the game' }) def get(self, game_id, guess): '''Guesses a game for a player''' game = session.query(Game).filter_by(game_id=game_id).first() word = session.query(Word).filter_by( word_id=game.word_id).first().word if not game: return "No game with game_id exists", 404 if guess not in game.guessed: new_guess = game.guessed + guess[0] else: new_guess = game.guessed new_correct = game.correct match = False game_over = False correct = "" status = 400 for i in range(0, 5): if word[i].lower() == guess.lower(): correct += word[i] match = True else: correct += new_correct[i] if '_' not in correct: game_over = True game.correct = correct game.guessed = new_guess if game_over: game.status = "Won" else: game.status = "progress" session.add(game) session.commit() result = game.serialize() if match: status = 200 result['message'] = "You guessed right!" else: result['message'] = "You were wrong!" result['guessed'] = list(game.guessed) result['correct'] = list(game.correct) del result['word_id'] return result, status @game_api.route('/<int:game_id>') class GetGame(Resource): @game_api.response(200, 'Success') @game_api.response(404, 'Not Found') @game_api.response(400, 'Bad Request') @game_api.doc(params={'game_id': 'The game_id of the game'}) def get(self, game_id): '''Guesses a game for a player''' game = session.query(Game).filter_by(game_id=game_id).first() return game.serialize(), 200
from flask import Flask from flask_restplus import Resource, Api, fields from func_task import blocked_slots, confirmed_block_slot , disallowed_slot ##################################### Flask App ############################################# app = Flask(__name__) api = Api(app) ################################## Input Data Model ################################################# time_format_model = api.model('Model', { "startTime": fields.String, "endTime": fields.String, }) list_model_input = api.model('ModelInput', { "user_a_block_slot": fields.List(fields.Nested(time_format_model)), "user_b_block_slot" : fields.List(fields.Nested(time_format_model)) }) list_model_confirmed_input = api.model('ModelConfirmed', { "user_a_block_slot": fields.List(fields.Nested(time_format_model)), "user_b_block_slot" : fields.List(fields.Nested(time_format_model)), "user_a_confirmed_meetings" : fields.List(fields.Nested(time_format_model)), "user_b_confirmed_meetings" :fields.List(fields.Nested(time_format_model)), # 'disallowed_slots' :fields.List(fields.Nested(time_format_model))
# And create the flask-restplus API api = Api(module_one, doc='/doc/', version='1.0', title='Module One API', description="""\ This is the API for Module One. It does the following: * Records greetings for users given by user name * Looks up the greeting for a user given by user name """) # This is the route namespace for the API ns = api.namespace("api", description="Module One API") # Describe the model used by the API m1 = api.model("Module One", { "user_name": fields.String(required=True, description="The name of the user"), "greeting": fields.String(description="A specific greeting for a user"), }) # the data store :) class UserGreetings(dict): def validate(self, data): if "user_name" not in data: abort(400, "Invalid request") user_greetings = UserGreetings() @ns.route("/greetings") class GreetingList(Resource): """ Shows a list of all greetings and allows you to POST a new greeting """
return render_template('index.html', year=now.year) """ Bellow this all code are relates to API """ api = Api(app, doc='/api/') data_model = api.model( 'Predict', { 'age': fields.Float(63), 'sex': fields.Float(1), 'cp': fields.Float(1), 'testbps': fields.Float(145), 'chol': fields.Float(233), 'fbs': fields.Float(1), 'restecg': fields.Float(2), 'thalach': fields.Float(150), 'exang': fields.Float(0.0), 'oldpeak': fields.Float(2.3), 'slope': fields.Float(3), 'ca': fields.Float(0.0), 'thal': fields.Float(6.0) }) @api.route('/predict') class Predict(Resource): def get(self): return "Hello API" @api.expect(data_model)
app.config.SWAGGER_UI_JSONEDITOR = True app.wsgi_app = ProxyFix(app.wsgi_app) CORS(app) api = Api( app, title='reFill 2', description='A set of APIs to interact with reFill, the citation-fixer' ) taskInfoModel = api.model('taskInfo', OrderedDict([ ('taskName', fields.String( required=True, description='Name of the submitted task', example='doSomething', )), ('taskId', fields.String( required=True, description='ID of the created task', example='942b3fb5-fe63-49cd-9b6d-230c36070d8f', )), ])) taskResponseModel = api.inherit('taskResponse', taskInfoModel, OrderedDict([ ('statusUrl', fields.String( required=True, description='URL to receive the status of the task', example='/status/doSomething/942b3fb5-fe63-49cd-9b6d-230c36070d8f', )), ('statusStreamUrl', fields.String( description='URL to receive a stream of the task status', example='/statusStream/doSomething/942b3fb5-fe63-49cd-9b6d-230c36070d8',
from flask import Flask from flask_restplus import Api, Resource, fields app = Flask(__name__) api = Api(app) a_language = api.model('Language', {'language': fields.String('The language.')}) languages = [] python = {'language': 'Python'} languages.append(python) @api.route('/language') class Language(Resource): def get(self): '''The get description ''' return languages @api.expect(a_language) def post(self): '''The other stuff for post''' languages.append(api.payload) return {'result': 'Language added'}, 201 if __name__ == '__main__': app.run(debug=True)
flow_param = OrderedDict([('prefix', 'milli'), ('volume_unit', 'litres'), ('time_unit', 'per_second')]) ## --- Choose session type --- ## app.config.from_object(__name__) app.config['test_session'] = True app.secret_key = 'secret_key' ## --- Flask-RESTPlus models --- ## config_setup = api.model( 'config setup', { 'dllDir': String(description='Path to dll directory', required=True, example='C:/Users/username/AppData/Local/QmixSDK'), 'configDir': String( description='Path to config directory', required=True, example= 'C:/Users/Public/Documents/QmixElements/Projects/default_project/Configurations/my_own_config' ) }) pump_client_request = api.model( 'Pumping request', { 'targetVolume': Float(description='Target volume', required=False, example=5.0), 'flowRate': Float(description='Flow rate', required=False, example=0.25) })
# requirements.txt): import json from flask import Flask, request from flask_restplus import Resource, fields, Api, Namespace from utils.matrix import elements_sum, diagonal_sum from utils.compression import encode app = Flask(__name__) api = Api(app, version='1.0', title='Test exercises', description='An API of test exercises') ns = api.namespace('TEST', description='Intelygenz talent test') matrix = api.model("matrix", {"matrix": fields.String("Elements of matrix.")}) string = api.model("string", {"string": fields.String("Word")}) # POST: /api/matrix/sum # ===================== # Debe devolver la suma de todos los elementos de una matriz # dada. Se debe implementar usando la función utils.matrix.elements_sum # Ejemplo de llamada: # -------------------------------------------------- # Content-Type: application/json # # { "matrix": [ [ 1, 2, 3], [4, 5, 6], [7, 8, 9] ] } # -------------------------------------------------- # Ejemplo de respuesta: # -------------------------------------------------- # Content-Type: application/json
title='Grading App', description='', ) add_student_api = api.namespace('addStudent', description='Assign student to the assignment') question_api = api.namespace('question', description='Question Management') # exposed apis student_api = api.namespace('student', description='Studet View') teacher_api = api.namespace('teacher', description='Teacher View') student_model = api.model( 'AssignStudent', { 'name': fields.String(required=True, description='Name of the student'), 'assignment_id': fields.String(required=True, description='Id of the assignment') }) question_model = api.model( 'AnswerQuestion', { 'studentId': fields.String(required=True, description='Id of the student'), 'assignmentId': fields.String(required=True, description='Id of the assignment'), 'answer': fields.String(required=True, description='Answer of the student'), 'marks': fields.Integer(required=True, description='Marks of the question'), })
from flask import Flask from flask_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): for todo in self.todos: if todo['id'] == id: return todo api.abort(404, "Todo {} doesn't exist".format(id)) def create(self, data): todo = data
import requests from flask import abort, Blueprint from flask_restplus import Api, fields, Resource from service import app blueprint_v1 = Blueprint('api-v1', __name__) api_v1 = Api( blueprint_v1, version='1.0', title='Ping Service', validate=True, ) ping = api_v1.model('Ping', { 'url': fields.String(required=True), }) @api_v1.route('/ping') class PingResource(Resource): @api_v1.expect(ping) def post(self): url = api_v1.payload['url'] try: response = requests.get(url, timeout=app.config['REQUEST_TIMEOUT']) except requests.RequestException: abort(400, f"Cannot access URL at '{url}'") if response.headers['Content-Type'] == 'application/json':
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()
text = remove_special_characters(text) return text flask_app = Flask(__name__) app = Api(app=flask_app, version="1.0", title="Movies Sentiment Classifier", description="Predict the sentiment of movies review") name_space = app.namespace('prediction', description='Prediction APIs') model = app.model( 'Prediction params', { 'review': fields.String(required=True, description="Text containing the review of movies", help="Text review cannot be blank") }) classifier = joblib.load('classifier_movies.joblib') vectorizer = joblib.load('count_vectorizer.joblib') @name_space.route("/") class MainClass(Resource): def options(self): response = make_response() response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add('Access-Control-Allow-Headers', "*") response.headers.add('Access-Control-Allow-Methods', "*")