def create_app(): Flask.response_class = JsonResponse app = Flask(__name__) app.config['CLASSIFIER_BASE_PATH'] = app.instance_path app.config.from_object('inspire_classifier.config') docs = FlaskApiSpec(app) @app.route("/api/health") def date(): """Basic endpoint that returns the date, used to check if everything is up and working.""" now = datetime.datetime.now() return jsonify(now) docs.register(date) @app.route("/api/predict/coreness", methods=["POST"]) @use_kwargs({ 'title': fields.Str(required=True), 'abstract': fields.Str(required=True) }) @marshal_with(serializers.ClassifierOutputSerializer) def core_classifier(**kwargs): """Endpoint for the CORE classifier.""" return predict_coreness(kwargs['title'], kwargs['abstract']) docs.register(core_classifier) return app @app.errorhandler(404) def page_not_found(e): return {"errors": [str(e)]}, 404
def set_routes(app: Flask, bp: Blueprint, docs: FlaskApiSpec): # a list of resources resources = [ (LocationResource, "/locations/<string:slug>/customers", "customers", ["POST"]), ] for resource, route, name, methods in resources: bp.add_url_rule(route, view_func=resource.as_view(name), methods=methods) app.register_blueprint(bp) for resource, route, name, methods in resources: docs.register(resource, blueprint=bp_name, endpoint=name)
def create_app(): app = Flask(__name__) app.config['PROPAGATE_EXCEPTIONS'] = True docs = FlaskApiSpec(app) app.add_url_rule('/data/<path:folder>/chunks', view_func=DataResource.as_view('DataResource')) docs.register(DataResource, endpoint='DataResource') app.add_url_rule('/status', view_func=Status.as_view('Status')) docs.register(Status, endpoint='Status') return app
def register_blueprints(app): app.register_blueprint(blueprints_blueprint, url_prefix=API_BASE_URL + 'blueprints') app.register_blueprint(jobs_blueprint, url_prefix=API_BASE_URL + 'jobs') app.register_blueprint(operations_blueprint, url_prefix=API_BASE_URL + 'operations') # Swagger docs = FlaskApiSpec(app) from .jobs.routes import get_job docs.register(get_job, blueprint="jobs")
def set_routes(app: Flask, bp: Blueprint, docs: FlaskApiSpec): # a list of resources resources = [ (ImageResource, "/search/", "img", ["GET"]), (ReverseImageResource, "/reverse_search/", "reverse_image", ["POST"]), ] for resource, route, name, methods in resources: bp.add_url_rule(route, view_func=resource.as_view(name), methods=methods) app.register_blueprint(bp) for resource, route, name, methods in resources: docs.register(resource, blueprint=bp_name, endpoint=name)
def set_routes(app: Flask, bp: Blueprint, docs: FlaskApiSpec): # a list of resources resources = [ (UsersResource, "/users/", "users", ["GET", "POST"]), (UserResource, "/users/<string:user_id>", "user", ["GET", "PATCH", "DELETE"]), ] for resource, route, name, methods in resources: bp.add_url_rule(route, view_func=resource.as_view(name), methods=methods) app.register_blueprint(bp) for resource, route, name, methods in resources: docs.register(resource, blueprint=bp_name, endpoint=name)
def create_app(env_name): app = Flask(__name__) app.config.from_object(app_config[env_name]) bcrypt.init_app(app) db.init_app(app) app.register_blueprint(user_blueprint, url_prefix='/garden/v1/users') app.register_blueprint(device_blueprint, url_prefix='/garden/v1/devices') docs = FlaskApiSpec(app) docs.register(devices.create, blueprint=device_blueprint) @app.route('/', methods=['GET']) def index(): return 'blah blah blah' return app
def register_spec(app): app.config.update({ "APISPEC_SPEC": APISpec( title="Flask VRFs API", version="0.0.1", openapi_version="2.0", plugins=[MarshmallowPlugin()], ), "APISPEC_SWAGGER_URL": "/api/docs/apispec.json", "APISPEC_SWAGGER_UI_URL": "/api/docs", }) docs = FlaskApiSpec(app) from app.api.vrf.views import Vrf docs.register(Vrf, blueprint="api") from app.api.vrfs.views import Vrfs docs.register(Vrfs, blueprint="api")
import flask import flask.views from flask_apispec import FlaskApiSpec app = flask.Flask(__name__) docs = FlaskApiSpec(app) @app.route('/pets/<pet_id>') @doc(params={'pet_id': {'description': 'pet id'}}) @marshal_with(PetSchema) @use_kwargs({'breed': ma.fields.Str()}) def get_pet(pet_id): return Pet('calici', 'cat') docs.register(get_pet) class MethodResourceMeta(ResourceMeta, flask.views.MethodViewType): pass class MethodResource(six.with_metaclass(MethodResourceMeta, flask.views.MethodView)): methods = None @doc( tags=['pets'], params={'pet_id': {'description': 'the pet name'}}, ) class CatResource(MethodResource): @marshal_with(PetSchema) def get(self, pet_id):
'/presidential/financial_summary/') api.add_resource(presidential.PresidentialBySizeView, '/presidential/contributions/by_size/') api.add_resource(presidential.PresidentialByStateView, '/presidential/contributions/by_state/') api.add_resource(presidential.PresidentialCoverageView, '/presidential/coverage_end_date/') app.config.update({ 'APISPEC_SWAGGER_URL': None, 'APISPEC_SWAGGER_UI_URL': None, 'APISPEC_SPEC': spec.spec, }) apidoc = FlaskApiSpec(app) apidoc.register(search.CandidateNameSearch, blueprint='v1') apidoc.register(search.CommitteeNameSearch, blueprint='v1') apidoc.register(candidates.CandidateView, blueprint='v1') apidoc.register(candidates.CandidateList, blueprint='v1') apidoc.register(candidates.CandidateSearch, blueprint='v1') apidoc.register(candidates.CandidateHistoryView, blueprint='v1') apidoc.register(committees.CommitteeView, blueprint='v1') apidoc.register(committees.CommitteeList, blueprint='v1') apidoc.register(committees.CommitteeHistoryView, blueprint='v1') apidoc.register(reports.ReportsView, blueprint='v1') apidoc.register(reports.CommitteeReportsView, blueprint='v1') apidoc.register(reports.EFilingHouseSenateSummaryView, blueprint='v1') apidoc.register(reports.EFilingPresidentialSummaryView, blueprint='v1') apidoc.register(reports.EFilingPacPartySummaryView, blueprint='v1') apidoc.register(totals.TotalsByCommitteeTypeView, blueprint='v1') apidoc.register(totals.CandidateTotalsView, blueprint='v1')
app.config.update({ 'APISPEC_SPEC': APISpec( title='s-prov', version='v1', plugins=['apispec.ext.marshmallow'], schemes=['http', 'https'], description= "S-ProvFlow provenance API - Provenance framework for storage and access of data-intensive streaming lineage. It offers a a web API and a range of dedicated visualisation tools and a provenance model (S-PROV) which utilises and extends PROV and ProvONE model" ), 'APISPEC_SWAGGER_URL': '/swagger/', }) docs = FlaskApiSpec(app) docs.register(insert_provenance) docs.register(wfexec_description_edit) docs.register(delete_workflow_run) docs.register(get_workflow_info) docs.register(get_workflowexecutions) #docs.register(get_instances_monitoring) docs.register(get_monitoring) docs.register(get_invocation_details) docs.register(get_instance_details) docs.register(filter_on_ancestor) docs.register(get_data_item) docs.register(get_data) docs.register(was_derived_from) docs.register(derived_data)
# Restful api configuration api = Api(app) api.add_resource(PersonApiList, "/v1/person/") api.add_resource(PersonApi, "/v1/person/<int:id>/") # Swagger documentation configuration app.config.update({ 'APISPEC_SPEC': APISpec( title='Test Chassis Service', version='1.0.0-b1', openapi_version="2.0", plugins=[MarshmallowPlugin()], info=dict( description="Flask resource chassis swagger documentation demo", license={ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html" })), 'APISPEC_SWAGGER_URL': '/swagger/', }) docs = FlaskApiSpec(app) docs.register(PersonApiList) docs.register(PersonApi) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5010)
'/api/cube/balances': Balances, '/api/cube/connection': ConnectionResource, '/api/cube/ex_pairs': ExPairResource, '/api/cube/save_setting': SaveCubeSetting, '/api/cube/transactions': Transactions, '/api/cube/valuations': Valuations, # Healthcheck '/health': Healthcheck, } for key, value in resources.items(): # Add API resources api.add_resource(value, key) # Register documentation docs.register(value) # Build the database: # This will create the database file using SQLAlchemy try: init_db() print('DB INITALIZED') except: app.logger.exception('Empty database. Unable to run init_db().') # This error handler is necessary for webargs usage with Flask-RESTful. @parser.error_handler def handle_request_parsing_error(err, req): abort(422, errors=err.messages)
address["city"] = get_first(results.get("city")) address["state"] = get_first(results.get("state")).upper() address["postcode"] = get_first(results.get("postcode")).upper() address["country"] = get_first(results.get("country")) return {k: v for k, v in address.items() if v} def get_first(l: List[str]) -> str: if l: return l[0] return "" @parser.error_handler def handle_request_parsing_error(err, req, schema, error_status_code, error_headers): """webargs error handler that uses Flask-RESTful's abort function to return a JSON error response to the client. """ abort(error_status_code, errors=err.messages) resources = [Parse, LibParse] for r in resources: url = re.sub("(?!^)([A-Z]+)", r"_\1", r.__name__).lower() api.add_resource(r, f"/{url}") docs.register(r) if __name__ == "__main__": app.run(debug=DEBUG)
title='Test Chassis Service', version='1.0.0-b1', openapi_version="2.0", # openapi_version="3.0.2", plugins=[MarshmallowPlugin()], info=dict(description= "Handles common resources shared by the entire architecture", license={ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html" })), 'APISPEC_SWAGGER_URL': '/swagger/', }) docs = FlaskApiSpec(flask_test_app) docs.register(TestApiList) docs.register(TestApi) docs.register(TestCountryList) docs.register(TestCountryApi) flask_test_app.register_error_handler(422, validation_error_handler) @flask_test_app.errorhandler(InvalidTokenError) def unauthorized(error): flask_test_app.logger.error("Authorization error: %s", error) return { "message": "You are not authorized to perform this request. " "Ensure you have a valid credentials before trying again" }, 401
api.add_resource(download.DownloadView, '/download/<path:path>/') api.add_resource(legal.UniversalSearch, '/legal/search/') api.add_resource(legal.GetLegalCitation, '/legal/citation/<citation_type>/<citation>') api.add_resource(legal.GetLegalDocument, '/legal/docs/<doc_type>/<no>') api.add_resource(load.Legal, '/load/legal/') app.config.update({ 'APISPEC_SWAGGER_URL': None, 'APISPEC_SWAGGER_UI_URL': None, 'APISPEC_SPEC': spec.spec, }) apidoc = FlaskApiSpec(app) apidoc.register(search.CandidateNameSearch, blueprint='v1') apidoc.register(search.CommitteeNameSearch, blueprint='v1') apidoc.register(candidates.CandidateView, blueprint='v1') apidoc.register(candidates.CandidateList, blueprint='v1') apidoc.register(candidates.CandidateSearch, blueprint='v1') apidoc.register(candidates.CandidateHistoryView, blueprint='v1') apidoc.register(committees.CommitteeView, blueprint='v1') apidoc.register(committees.CommitteeList, blueprint='v1') apidoc.register(committees.CommitteeHistoryView, blueprint='v1') apidoc.register(reports.ReportsView, blueprint='v1') apidoc.register(reports.CommitteeReportsView, blueprint='v1') apidoc.register(reports.EFilingSummaryView, blueprint='v1') apidoc.register(totals.TotalsView, blueprint='v1') apidoc.register(totals.CandidateTotalsView, blueprint='v1') apidoc.register(sched_a.ScheduleAView, blueprint='v1') apidoc.register(sched_a.ScheduleAEfileView, blueprint='v1')
def init_swagger(app): docs = FlaskApiSpec(app) docs.register(UsersController) docs.register(UserController) return docs
from flask_apispec import FlaskApiSpec app = flask.Flask(__name__) docs = FlaskApiSpec(app) @app.route('/pets/<pet_id>') @doc(params={'pet_id': {'description': 'pet id'}}) @marshal_with(PetSchema) @use_kwargs({'breed': ma.fields.Str()}) def get_pet(pet_id): return Pet('calici', 'cat') docs.register(get_pet) class MethodResourceMeta(ResourceMeta, flask.views.MethodViewType): pass class MethodResource( six.with_metaclass(MethodResourceMeta, flask.views.MethodView)): methods = None @doc( tags=['pets'], params={'pet_id': { 'description': 'the pet name'
def __init__(self, name, type): self.name = name self.type = type class PetSchema(ma.Schema): name = ma.fields.Str() type = ma.fields.Str() import flask import flask.views from flask_apispec import FlaskApiSpec app = flask.Flask(__name__) docs = FlaskApiSpec(app) @app.route('/pets/<pet_id>') @doc(params={'pet_id': {'description': 'pet id'}}) @marshal_with(PetSchema) @use_kwargs({'breed': ma.fields.Str()}) def get_pet(pet_id): return Pet('haha', 'cat') docs.register(get_pet) if __name__ == '__main__': app.run(debug=True, host="0.0.0.0")
""" def get(self): response = transport_hlt.get_status() return response @use_kwargs({'target_liters': fields.Integer()}) def post(self, target_liters): return transport_hlt.fill_to(target_liters) @use_kwargs({'amount': fields.Float()}) def delete(self, amount): return transport_hlt.post('transfer', amount) app.add_url_rule('/hlt', view_func=HLT.as_view('hlt')) docs.register(HLT) @doc(description='Temp') class BrewPiTemp(MethodResource): """ Read/Write temperature on the BrewPi """ def get(self): return transport.get_temperatures() @use_kwargs({'fridge': fields.Float()}) @use_kwargs({'beer': fields.Float()}) def post(self, beer=None, fridge=None): if beer: return transport.set_beer_setpoint(beer)
def fd_app(cache_dir): """ API app for FreeDiscovery """ if not os.path.exists(cache_dir): raise ValueError('Cache_dir {} does not exist!'.format(cache_dir)) app = Flask('freediscovery_api') app.url_map.strict_slashes = False app.config.update({ 'APISPEC_SPEC': APISpec(title='FreeDiscovery', version='v0', plugins=['apispec.ext.marshmallow']), 'APISPEC_SWAGGER_URL': '/openapi-specs.json', 'APISPEC_SWAGGER_UI_URL': '/swagger-ui.html' }) app.test_client_class = TestClient docs = FlaskApiSpec(app) #app.config['DEBUG'] = False ## Actually setup the Api resource routing here for resource_el, url in [ (ExampleDatasetApi, "/example-dataset/<name>"), (FeaturesApi, "/feature-extraction"), (FeaturesApiElement, '/feature-extraction/<dsid>'), (FeaturesApiElementMappingNested, '/feature-extraction/<dsid>/id-mapping'), (EmailParserApi, "/email-parser"), (EmailParserApiElement, '/email-parser/<dsid>'), (EmailParserApiElementIndex, '/email-parser/<dsid>/index'), (ModelsApi, '/categorization/'), (ModelsApiElement, '/categorization/<mid>'), (ModelsApiPredict, '/categorization/<mid>/predict'), (LsiApi, '/lsi/'), (LsiApiElement, '/lsi/<mid>'), (KmeanClusteringApi, '/clustering/k-mean/'), (BirchClusteringApi, '/clustering/birch'), (WardHCClusteringApi, '/clustering/ward_hc'), (DBSCANClusteringApi, '/clustering/dbscan'), (ClusteringApiElement, '/clustering/<method>/<mid>'), (DupDetectionApi, '/duplicate-detection/'), (DupDetectionApiElement, '/duplicate-detection/<mid>'), (MetricsCategorizationApiElement, '/metrics/categorization'), (MetricsClusteringApiElement, '/metrics/clustering'), (MetricsDupDetectionApiElement, '/metrics/duplicate-detection'), (EmailThreadingApi, '/email-threading/'), (EmailThreadingApiElement, '/email-threading/<mid>'), (SearchApi, '/search/'), (CustomStopWordsApi, '/stop-words/'), (CustomStopWordsLoadApi, '/stop-words/<name>'), #(CatchAll , "/<url>") ]: # monkeypatching, not great resource_el._cache_dir = cache_dir resource_el.methods = ['GET', 'POST', 'DELETE'] #api.add_resource(resource_el, '/api/v0' + url, strict_slashes=False) ressource_name = resource_el.__name__ app.add_url_rule('/api/v0' + url, view_func=resource_el.as_view(ressource_name)) if ressource_name not in ["EmailThreadingApi"]: # the above two cases fail due to recursion limit docs.register(resource_el, endpoint=ressource_name) @app.errorhandler(500) def handle_error(error): #response = jsonify(error.to_dict()) response = jsonify({'messages': str(error)}) response.status_code = 500 return response @app.errorhandler(404) def handle_404_error(error): response = jsonify({"messages": str(error)}) response.status_code = 404 return response @app.errorhandler(400) def handle_400_error(error): response = jsonify({"messages": str(error)}) response.status_code = 400 return response @app.errorhandler(422) def handle_422_error(error): # marshmallow error response = jsonify(error.data) response.status_code = 422 return response return app
filings.FilingsView, '/committee/<committee_id>/filings/', '/candidate/<candidate_id>/filings/', ) api.add_resource(filings.FilingsList, '/filings/') api.add_resource(download.DownloadView, '/download/<path:path>/') app.config.update({ 'APISPEC_SWAGGER_URL': None, 'APISPEC_SWAGGER_UI_URL': None, 'APISPEC_SPEC': spec.spec, }) apidoc = FlaskApiSpec(app) apidoc.register(search.CandidateNameSearch, blueprint='v1') apidoc.register(search.CommitteeNameSearch, blueprint='v1') apidoc.register(candidates.CandidateView, blueprint='v1') apidoc.register(candidates.CandidateList, blueprint='v1') apidoc.register(candidates.CandidateSearch, blueprint='v1') apidoc.register(candidates.CandidateHistoryView, blueprint='v1') apidoc.register(committees.CommitteeView, blueprint='v1') apidoc.register(committees.CommitteeList, blueprint='v1') apidoc.register(committees.CommitteeHistoryView, blueprint='v1') apidoc.register(reports.ReportsView, blueprint='v1') apidoc.register(totals.TotalsView, blueprint='v1') apidoc.register(sched_a.ScheduleAView, blueprint='v1') apidoc.register(sched_b.ScheduleBView, blueprint='v1') apidoc.register(sched_e.ScheduleEView, blueprint='v1') apidoc.register(costs.CommunicationCostView, blueprint='v1') apidoc.register(costs.ElectioneeringView, blueprint='v1')
from apispec import APISpec app.config.update({ 'APISPEC_SPEC': APISpec( title='s-prov', version='v1', plugins=['apispec.ext.marshmallow'], schemes=['http','https'], description="S-ProvFlow provenance API - Provenance framework for storage and access of data-intensive streaming lineage. It offers a a web API and a range of dedicated visualisation tools and a provenance model (S-PROV) which utilises and extends PROV and ProvONE model" ), 'APISPEC_SWAGGER_URL': '/swagger/', }) docs = FlaskApiSpec(app) docs.register(insert_provenance) docs.register(wfexec_description_edit) docs.register(delete_workflow_run) docs.register(get_workflow_info) docs.register(get_workflowexecutions) #docs.register(get_instances_monitoring) docs.register(get_monitoring) docs.register(get_invocation_details) docs.register(get_instance_details) docs.register(filter_on_ancestor) docs.register(get_data_item) docs.register(get_data) docs.register(was_derived_from) docs.register(derived_data)
from flask_apispec import FlaskApiSpec app = flask.Flask(__name__) docs = FlaskApiSpec(app) @app.route('/pets/<pet_id>') @doc(params={'pet_id': {'description': 'pet id'}}) @marshal_with(PetSchema) @use_kwargs({'breed': ma.fields.Str()}) def get_pet(pet_id): return Pet('calici', 'cat') docs.register(get_pet) class MethodResourceMeta(ResourceMeta, flask.views.MethodViewType): pass class MethodResource(flask.views.MethodView, metaclass=MethodResourceMeta): methods = None @doc( tags=['pets'], params={'pet_id': { 'description': 'the pet name' }},
try: data = jwt.decode(token, os.environ['JWT_ENCODE']) current_user = '******' except: return jsonify({'message': 'token is invalid'}) return f(current_user, *args, **kwargs) return decorator # Retrieves a given user in path @app.route('/user/<email_address>', methods=['GET']) @token_required @marshal_with(LoginResponseSchema, code=200) @marshal_with(ErrorSchema, code=400) def user_handle(email_address): body = {"email": email_address} user_object = User(body) result = user_object.get_user() if result['statusCode'] == 200: return result['response'], 200 return result['response'], 400 # Perform auto-documentation docs = FlaskApiSpec(app) docs.register(login) docs.register(user_handle) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
from flask_apispec import FlaskApiSpec from .skin_detect import * import os from flask import Flask, flash, request, redirect, url_for from werkzeug.utils import secure_filename import cv2 from flask import jsonify app = Flask(__name__) docs = FlaskApiSpec(app) app.add_url_rule('/skin_detect', view_func=ImageEndPoint.as_view('skin_detect')) docs.register(ImageEndPoint, endpoint="skin_detect") import skin_detector UPLOAD_FOLDER = './uploads' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST'])
def __init__(self, name, type): self.name = name self.type = type class PetSchema(Schema): name = fields.Str() type = fields.Str() pet_schema = PetSchema( only=['name', 'type']) from flask import Flask, views from flask_apispec import FlaskApiSpec app = Flask(__name__) docs = FlaskApiSpec(app) @app.route("/pets/<pet_id>") @doc(params={'pet_id': {'description': 'pet_id'}}) # swagger @marshal_with(pet_schema) def get_pet(pet_id): return Pet('hehe', 'cat') docs.register(get_pet) # register method get_pet to swagger if __name__ == "__main__": app.run(host='0.0.0.0', debug=True)
class Documentation: def __init__(self, app): app.config.update({ 'APISPEC_SPEC': APISpec( title='KodeSmil Flask', version='v1', openapi_version="3.0.2", info=dict(description='KodeSmil microservices API'), plugins=[MarshmallowPlugin()], ), 'APISPEC_SWAGGER_UI_URL': '/docs/', }) self.docs = FlaskApiSpec(app) self._initialize() def _initialize(self): self.docs.register( views.get_services, endpoint='get_services', blueprint='products', ) self.docs.register( views.add_service, endpoint='add_service', blueprint='products', ) self.docs.register( views.filter_services, endpoint='filter_services', blueprint='products', ) self.docs.register( views.get_service_categories, endpoint='get_service_categories', blueprint='products', ) self.docs.register( views.get_service_providers, endpoint='get_service_providers', blueprint='products', ) self.docs.register( views.add_service_provider, endpoint='add_service_provider', blueprint='products', ) self.docs.register( views.get_service_slots, endpoint='get_service_slots', blueprint='products', ) self.docs.register( views.add_service_slot, endpoint='add_service_slot', blueprint='products', )
api.add_resource(filings.FilingsList, '/filings/') api.add_resource(download.DownloadView, '/download/<path:path>/') api.add_resource(legal.UniversalSearch, '/legal/search/') api.add_resource(legal.GetLegalCitation, '/legal/citation/<citation_type>/<citation>') api.add_resource(legal.GetLegalDocument, '/legal/docs/<doc_type>/<no>') app.config.update({ 'APISPEC_SWAGGER_URL': None, 'APISPEC_SWAGGER_UI_URL': None, 'APISPEC_SPEC': spec.spec, }) apidoc = FlaskApiSpec(app) apidoc.register(search.CandidateNameSearch, blueprint='v1') apidoc.register(search.CommitteeNameSearch, blueprint='v1') apidoc.register(candidates.CandidateView, blueprint='v1') apidoc.register(candidates.CandidateList, blueprint='v1') apidoc.register(candidates.CandidateSearch, blueprint='v1') apidoc.register(candidates.CandidateHistoryView, blueprint='v1') apidoc.register(committees.CommitteeView, blueprint='v1') apidoc.register(committees.CommitteeList, blueprint='v1') apidoc.register(committees.CommitteeHistoryView, blueprint='v1') apidoc.register(reports.ReportsView, blueprint='v1') apidoc.register(reports.CommitteeReportsView, blueprint='v1') apidoc.register(reports.EFilingHouseSenateSummaryView, blueprint='v1') apidoc.register(reports.EFilingPresidentialSummaryView, blueprint='v1') apidoc.register(reports.EFilingPacPartySummaryView, blueprint='v1') apidoc.register(totals.TotalsView, blueprint='v1') apidoc.register(totals.CandidateTotalsView, blueprint='v1')
api.add_resource( filings.FilingsView, '/committee/<committee_id>/filings/', '/candidate/<candidate_id>/filings/', ) api.add_resource(filings.FilingsList, '/filings/') app.config.update({ 'APISPEC_SWAGGER_URL': None, 'APISPEC_SWAGGER_UI_URL': None, 'APISPEC_SPEC': spec.spec, }) apidoc = FlaskApiSpec(app) apidoc.register(CandidateNameSearch, blueprint='v1') apidoc.register(CommitteeNameSearch, blueprint='v1') apidoc.register(candidates.CandidateView, blueprint='v1') apidoc.register(candidates.CandidateList, blueprint='v1') apidoc.register(candidates.CandidateSearch, blueprint='v1') apidoc.register(candidates.CandidateHistoryView, blueprint='v1') apidoc.register(committees.CommitteeView, blueprint='v1') apidoc.register(committees.CommitteeList, blueprint='v1') apidoc.register(committees.CommitteeHistoryView, blueprint='v1') apidoc.register(reports.ReportsView, blueprint='v1') apidoc.register(totals.TotalsView, blueprint='v1') apidoc.register(sched_a.ScheduleAView, blueprint='v1') apidoc.register(sched_b.ScheduleBView, blueprint='v1') apidoc.register(sched_e.ScheduleEView, blueprint='v1') apidoc.register(aggregates.ScheduleABySizeView, blueprint='v1') apidoc.register(aggregates.ScheduleAByStateView, blueprint='v1')
app.config.from_object(config) app.url_map.strict_slashes = False app.config.update({'APISPEC_SPEC': spec}) jwt = JWTAuth(app) api = Api(app) api.add_resource(Users, '/users') api.add_resource(LogIn, '/login') api.add_resource(LogOut, '/logout') api.add_resource(ToDosGetAllPost, '/todos/<string:username>') api.add_resource(ToDosGetByIdPutDelete, '/todos/<string:username>/<int:todo_id>') docs = FlaskApiSpec(app) docs.register(Users) docs.register(LogIn) docs.register(LogOut) docs.register(ToDosGetAllPost) docs.register(ToDosGetByIdPutDelete) fields_to_add_bearer_security_check = { '/logout': ('get', ), '/todos/{username}': ('get', 'post'), '/todos/{username}/{todo_id}': ('get', 'put', 'delete') } update_paths_with_bearer_security_check(spec, fields_to_add_bearer_security_check) if __name__ == '__main__': init_db()
book = BookModel(name=name, **data) db.session.add(book) db.session.commit() return book.json() @marshal_with(AwesomeResponseSchema) def delete(self, name): '''Takes in a number n, returns the square of n''' book = BookModel.query.filter_by(name=name).first() if book: # if book is found, Store db.session.delete(book) db.session.commit() assert book, "deleted book" return {'message': 'Deleted'} else: # return error return {'message': 'book not found'}, 404 API.add_resource(BooksView, '/books') API.add_resource(BookView, '/book/<string:name>') DOCS.register(BooksView) APP.debug = True if __name__ == '__main__': APP.run(host='localhost', port=5000)
def build_routes(app): """Register routes to given app instance.""" app.config.update({ 'APISPEC_SPEC': APISpec( title=SERVICE_NAME, openapi_version=OPENAPI_VERSION, version=API_VERSION, plugins=[MarshmallowPlugin()], ), 'APISPEC_SWAGGER_URL': API_SPEC_URL, }) app.register_blueprint(cache_blueprint) app.register_blueprint(dataset_blueprint) swaggerui_blueprint = get_swaggerui_blueprint( SWAGGER_URL, API_SPEC_URL, config={'app_name': 'Renku Service'}) app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL) docs = FlaskApiSpec(app) docs.register(upload_file_view, blueprint=CACHE_BLUEPRINT_TAG) docs.register(list_uploaded_files_view, blueprint=CACHE_BLUEPRINT_TAG) docs.register(project_clone, blueprint=CACHE_BLUEPRINT_TAG) docs.register(list_projects_view, blueprint=CACHE_BLUEPRINT_TAG) docs.register(create_dataset_view, blueprint=DATASET_BLUEPRINT_TAG) docs.register(add_file_to_dataset_view, blueprint=DATASET_BLUEPRINT_TAG) docs.register(list_datasets_view, blueprint=DATASET_BLUEPRINT_TAG) docs.register(list_dataset_files_view, blueprint=DATASET_BLUEPRINT_TAG)
class Spec: def __init__(self, app, url, **config): app.config.update({ 'APISPEC_SPEC': APISpec(**config, plugins=[MarshmallowPlugin()], **self.__default_security_schema()), 'APISPEC_SWAGGER_UI_URL': url, 'APISPEC_SWAGGER_URL': url + '.json' }) self.app = app self.doc = FlaskApiSpec(app) self.__register_security_schema() def register_blueprint(self, blueprint): try: for function_name, rules in self.app.url_map._rules_by_endpoint.items( ): for rule in rules: if self.__belongs_to_blueprint(function_name, blueprint): view_function = self.app.view_functions[function_name] self.doc.register(view_function, blueprint=blueprint.name) self.__prepare_routes(rule, view_function) except: traceback.print_exc() def __prepare_routes(self, endpoint, view_function): converter = SwaggerConverter(self.app, self.doc.spec) swagger_formatted_endpoint = converter.get_path( endpoint, view_function)['path'] self.__remove_options_for_all_methods(swagger_formatted_endpoint) method_documentations = self.__get_all_method_documentations( swagger_formatted_endpoint, endpoint.methods) self.__prepare_tenant_header_for_methods(method_documentations) self.__write_security_description_for_methods(method_documentations) def __remove_options_for_all_methods(self, endpoint): path, all_path_methods = self.__documentation_path_for_endpoint( endpoint) self.__remove_options(path, all_path_methods) def __prepare_tenant_header_for_methods(self, method_documentations): for method_documentation in method_documentations: if method_documentation.get('tenant_required', True): self.__register_tenant_header(method_documentation) def __get_all_method_documentations(self, endpoint, method_names): path, all_methods_documentations = self.__documentation_path_for_endpoint( endpoint) methods_documentations = [ method for method_name, method in all_methods_documentations.items() if method_name.upper() in method_names ] return methods_documentations def __remove_options(self, path, methods): self.doc.spec._paths[path] = { method_name: args for method_name, args in methods.items() if method_name != 'options' } def __register_tenant_header(self, method_documentation): method_documentation.setdefault('parameters', []).insert( 0, self.__tenant_header_parameter()) def __register_security_schema(self): self.doc.spec.components.security_scheme( 'access_token', dict(type='http', scheme='bearer')) def __documentation_path_for_endpoint(self, endpoint): for path, methods in self.__all_documentation_paths(): if path == endpoint: return path, methods return None, [] def __all_documentation_paths(self): return self.doc.spec._paths.items() @staticmethod def __write_security_description_for_methods(method_documentations): for method_documentation in method_documentations: Spec.__write_security_description(method_documentation) @staticmethod def __write_security_description(method_documentation): existing_description = method_documentation.get('description', '') visibility = method_documentation.get("access", "N/A") description = textwrap.dedent(f''' {existing_description} # Security **Visibility**: ```{visibility}``` ''') roles = method_documentation.get('roles', []) if roles: role_list = "\n".join(f'* {role}' for role in roles) description += f'**Roles**:\n\n{role_list}' method_documentation.setdefault('description', description) @staticmethod def __belongs_to_blueprint(function_name, blueprint): return function_name.startswith(blueprint.name) @staticmethod def __tenant_header_parameter(): return { 'in': 'header', 'name': 'x-tenant', 'required': True, 'schema': { 'type': 'integer' } } @staticmethod def __default_security_schema(): return {"security": [dict(access_token=[])]}