def run(): template = args.template app = pkg_resources.EntryPoint.parse("x=%s" % args.app).load(False) if template is not None: with open(template, 'r') as f: spec = swagger(app, template=json.loads(f.read())) else: spec = swagger(app) if args.out_dir is None: print json.dumps(spec, indent=4) else: with open("%s/swagger.json" % args.out_dir, 'w') as f: f.write(json.dumps(spec, indent=4)) f.close()
def test_duplicate_identifier(self): swagger_spec = swagger(self.app) identifier = Identifier(system='https://unique.org', value='abc123') data = swagger_spec['definitions']['QuestionnaireResponse']['example'] data['identifier'] = identifier.as_fhir() self.promote_user(role_name=ROLE.PATIENT.value) self.login() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data) assert response.status_code == 200 # Submit a second, with the same identifier, expect error data2 = swagger_spec['definitions']['QuestionnaireResponse']['example'] data2['identifier'] = identifier.as_fhir() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data2) assert response.status_code == 409 self.test_user = db.session.merge(self.test_user) assert self.test_user.questionnaire_responses.count() == 1 # And a third, with just the id.value changed data3 = swagger_spec['definitions']['QuestionnaireResponse']['example'] identifier.value = 'do-over' data3['identifier'] = identifier.as_fhir() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data3) assert response.status_code == 200 self.test_user = db.session.merge(self.test_user) assert self.test_user.questionnaire_responses.count() == 2
def run(): app = pkg_resources.EntryPoint.parse("x=%s" % args.app).load(False) # load the base template template = None if args.template is not None: with open(args.template, 'r') as f: template = json.loads(f.read()) # overwrite template with specified arguments if args.definitions is not None: with open(args.definitions, 'r') as f: rawdefs = json.loads(f.read()) if 'definitions' in rawdefs: rawdefs = rawdefs['definitions'] for d in rawdefs.keys(): template['definitions'][d] = rawdefs[d] spec = swagger(app, template=template) if args.host is not None: spec['host'] = args.host if args.base_path is not None: spec['basePath'] = args.base_path if args.version is not None: spec['info']['version'] = args.version if args.out_dir is None: print json.dumps(spec, indent=4) else: with open("%s/swagger.json" % args.out_dir, 'w') as f: f.write(json.dumps(spec, indent=4)) f.close()
def swagger_spec(): # Get swagger application. swag = swagger(app) swag['info']['title'] = configuration.APP_NAME swag['info']['version'] = configuration.VERSION return swag
def spec(): swag = swagger(app, ) swag['info']['version'] = 'v1' swag['info']['title'] = 'trueskill360' swag['info']['description'] = ''' a webservice wrapping the open source trueskill.org library NOTE: this api does not persist data _mu_ = ~skill (or lower boundary of skill) _sigma_ = uncertainty that _mu_ is correct _exposure_ = leaderboard sort key. considers skill (_mu_) and confidence that skill is correct (_sigma_) STORE ALL THESE VALUES WITH HIGH PRECISION DO NOT ATTEMPT TO ADJUST THESE VALUES IF YOU HAVE A STORED _mu_ AND _sigma_ FOR A PLAYER YOU MUST SEND THEM OR WE WILL ASSUME ITS A NEW PLAYER WITH DEFAULT ENTRY SKILL order leaderboards by _exposure_ DESC. the more matches are played the lower `sigma` falls. the more `sigma` falls over time `exposure` trends upward. this means that the person with more games (higher confidence in _mu_) will be placed slightly higher on leaderboard than somebody who may have same skill but a lower confidence that its correct. _quality_ = 0f-1f chance the match will draw. high quality is a "even" match. low quality is a stomp _probability_ = .5f-1f chance the _favor_ed player will win. high prob is a stomp, low prob is a "even" match _favor_ = player with the higher _exposure_ YOU MAY MULTIPLY _quality_ AND _probability_ BY 100 TO GET AN EASIER TO READ PERCENTAGE (i.e. 73% chance to win) ''' return jsonify(swag)
def specs(): """ Provides Swagger specification for the CSDH API --- tags: - Base responses: '200': description: Swagger specification type: object default: description: Unexpected error schema: $ref: "#/definitions/Message" """ swag = swagger(app) swag['info']['version'] = "0.0.1" swag['info']['title'] = "CSDH API" swag['info']['description'] = """API Specification for the CLARIAH Structured Data Hub""" # swag['host'] = "api.clariah-sdh.eculture.labs.vu.nl" swag['host'] = app.config['SERVER_NAME'] swag['schemes'] = ['http'] swag['basePath'] = '/' swag['swagger'] = '2.0' return jsonify(swag)
def spec(): prefix = current_app.config.get('SWAGGER_UI_API_PREFIX', None) swag = swagger(current_app) swag.update(SwaggerUI().spec) swag.update({'host': get_netloc()}) return jsonify(swag)
def api_doc(): swagger_conf = swagger(app) # General declarations swagger_conf['info']['version'] = "1.0" swagger_conf['info']['title'] = "QuestionTime API" #You can change this if you don't want to use the production basepath swagger_conf['host'] = 'safe-oasis-74257.herokuapp.com' swagger_conf['schemes'] = ['https'] return jsonify(swagger_conf)
def test_submit_assessment_for_qb(self): swagger_spec = swagger(self.app) data = swagger_spec['definitions']['QuestionnaireResponse']['example'] rp = ResearchProtocol(name='proto') with SessionScope(db): db.session.add(rp) db.session.commit() rp = db.session.merge(rp) rp_id = rp.id qn = self.add_questionnaire(name='epic26') org = Organization(name="testorg") org.research_protocols.append(rp) with SessionScope(db): db.session.add(qn) db.session.add(org) db.session.commit() qn, org = map(db.session.merge, (qn, org)) qb = QuestionnaireBank( name='Test Questionnaire Bank', classification='baseline', research_protocol_id=rp_id, start='{"days": 0}', overdue='{"days": 7}', expired='{"days": 90}') qbq = QuestionnaireBankQuestionnaire(questionnaire=qn, rank=0) qb.questionnaires.append(qbq) test_user = get_user(TEST_USER_ID) test_user.organizations.append(org) authored = FHIR_datetime.parse(data['authored']) audit = Audit(user_id=TEST_USER_ID, subject_id=TEST_USER_ID) uc = UserConsent( user_id=TEST_USER_ID, organization=org, audit=audit, agreement_url='http://no.com', acceptance_date=authored) with SessionScope(db): db.session.add(qb) db.session.add(test_user) db.session.add(audit) db.session.add(uc) db.session.commit() self.promote_user(role_name=ROLE.PATIENT.value) self.login() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data) assert response.status_code == 200 test_user = get_user(TEST_USER_ID) qb = db.session.merge(qb) assert test_user.questionnaire_responses.count() == 1 assert ( test_user.questionnaire_responses[0].questionnaire_bank_id == qb.id)
def test_invalid_identifier(self): swagger_spec = swagger(self.app) identifier = Identifier(system=None, value='abc-123') data = swagger_spec['definitions']['QuestionnaireResponse']['example'] data['identifier'] = identifier.as_fhir() self.promote_user(role_name=ROLE.PATIENT.value) self.login() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data) assert response.status_code == 400
def test_invalid_status(self): swagger_spec = swagger(self.app) data = swagger_spec['definitions']['QuestionnaireResponse']['example'] data.pop('identifier') data['status'] = 'in-progress' self.promote_user(role_name=ROLE.PATIENT.value) self.login() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data) assert response.status_code == 400
def specs(): swag = swagger(app) swag['info']['version'] = "0.0.1" swag['info']['title'] = "CSDH Inspector API" swag['info']['description'] = "API for the CLARIAH Structured Data Hub Inspector" swag['host'] = "localhost:5000" swag['schemes'] = ['http'] swag['basePath'] = '/' swag['swagger'] = '2.0' return jsonify(swag)
def spec(): """ Returns the swagger spec. Read more by this link https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md :return: """ swag = swagger(app) swag['info']['title'] = app.name swag['consumes'] = ['application/json'] swag['produces'] = ['application/json'] return jsonify(swag)
def spec(): host = request.url_root.rstrip('/').replace(app.config['WSGI_STR'], '') return jsonify(swagger(app, from_file_keyword="swagger_from_file", template={ "host": host.replace('http://', ''), "info": { "version": "1.0", "title": "WQP Sites service" } }))
def test_swagger_docgen(self): """Build swagger docs for entire project""" expected_keys = ( 'info', 'paths', 'swagger', 'definitions', ) swag = swagger(self.client.application) for key in expected_keys: assert key in swag
def validate_document(document): """Validate given JSON document against our swagger schema""" swag = swagger(current_app) draft4_schema = { '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'object', 'definitions': swag['definitions'], } validation_schema = 'QuestionnaireResponse' # Copy desired schema (to validate against) to outermost dict draft4_schema.update(swag['definitions'][validation_schema]) jsonschema.validate(document, draft4_schema)
def spec(): """View that exposes a JSON spec from API to use in swagger-ui""" swag = swagger(current_app) swag['info'] = { 'version': '2.0', 'title': 'Flapy Auth-API', 'description': 'All content of web application in API for Apps', } swag['swagger'] = '2.0' swag['produces'] = ['application/json; charset=utf-8'] swag['consumes'] = ['application/json; charset=utf-8'] return jsonify(swag)
def get(self): """ Generate YAML feed suitable for Swagger UI to consume --- tags: - docs responses: 200: description: Swagger YAML successfully generated """ swag = swagger(current_app) swag['info']['title'] = "Flask-Rest" swag['info']['description'] = "Flask-Rest turbocharged Rest/MicroService Development" swag['info']['version'] = "0.1.0" return jsonify(swag)
def test_submit_assessment(self): swagger_spec = swagger(self.app) data = swagger_spec['definitions']['QuestionnaireResponse']['example'] self.promote_user(role_name=ROLE.PATIENT.value) self.login() response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=data) assert response.status_code == 200 response = response.json assert response['ok'] assert response['valid'] self.test_user = db.session.merge(self.test_user) assert self.test_user.questionnaire_responses.count() == 1 assert ( self.test_user.questionnaire_responses[0].encounter.auth_method == 'password_authenticated')
def api_spec(): swag = swagger(app) swag['info']['title'] = "DOAJ API documentation" # Generate the swagger description from the Jinja template account_url = None if current_user.is_authenticated: account_url = url_for('account.username', username=current_user.id, _external=True, _scheme=app.config.get('PREFERRED_URL_SCHEME', 'https')) swag['info']['description'] = render_template('api/v1/swagger_description.html', api_version=API_VERSION_NUMBER, base_url=url_for('.api_v1_root', _external=True, _scheme=app.config.get('PREFERRED_URL_SCHEME', 'https')), contact_us_url=url_for('doaj.contact'), account_url=account_url) swag['info']['version'] = API_VERSION_NUMBER return make_response((jsonify(swag), 200, {'Access-Control-Allow-Origin': '*'}))
def test_update_assessment(self): swagger_spec = swagger(self.app) completed_qnr = swagger_spec['definitions']['QuestionnaireResponse'][ 'example'] instrument_id = (completed_qnr['questionnaire']['reference'].split( '/')[-1]) questions = completed_qnr['group']['question'] incomplete_questions = [] # Delete answers for second half of QuestionnaireResponse for index, question in enumerate(questions): question = question.copy() if (index > len(questions) / 2): question.pop('answer', []) incomplete_questions.append(question) in_progress_qnr = completed_qnr.copy() in_progress_qnr.update({ 'status': 'in-progress', 'group': {'question': incomplete_questions}, }) self.login() self.bless_with_basics() self.promote_user(role_name=ROLE.STAFF.value) # Upload incomplete QNR in_progress_response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=in_progress_qnr) assert in_progress_response.status_code == 200 # Update incomplete QNR update_qnr_response = self.client.put( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=completed_qnr) assert update_qnr_response.status_code == 200 assert update_qnr_response.json['ok'] assert update_qnr_response.json['valid'] updated_qnr_response = self.client.get( '/api/patient/assessment?instrument_id={}'.format(instrument_id)) assert update_qnr_response.status_code == 200 assert ( updated_qnr_response.json['entry'][0]['group'] == completed_qnr['group'])
def test_no_update_assessment(self): swagger_spec = swagger(self.app) qnr = swagger_spec['definitions']['QuestionnaireResponse']['example'] self.promote_user(role_name=ROLE.PATIENT.value) self.login() # Upload QNR qnr_response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=qnr) assert qnr_response.status_code == 200 qnr['identifier']['system'] = 'foo' # Attempt to update different QNR; should fail update_qnr_response = self.client.put( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=qnr) assert update_qnr_response.status_code == 404
def test_assessments_csv(self): swagger_spec = swagger(self.app) example_data = swagger_spec['definitions']['QuestionnaireResponse'][ 'example'] instrument_id = example_data['questionnaire']['reference'].split('/')[ -1] self.promote_user(role_name=ROLE.PATIENT.value) self.login() upload_response = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=example_data) assert upload_response.status_code == 200 download_response = self.client.get( '/api/patient/assessment', query_string={'format': 'csv', 'instrument_id': instrument_id} ) csv_string = download_response.get_data(as_text=True) assert len(csv_string.split("\n")) > 1
def run(): app = pkg_resources.EntryPoint.parse("x=%s" % args.app).load(False).app # load the base template template = None if args.template is not None: with open(args.template, 'r') as f: template = json.loads(f.read()) # overwrite template with specified arguments if args.definitions is not None: with open(args.definitions, 'r') as f: rawdefs = json.loads(f.read()) if 'definitions' in rawdefs: rawdefs = rawdefs['definitions'] for d in rawdefs.keys(): template['definitions'][d] = rawdefs[d] spec = swagger(app, template=template) if args.host is not None: spec['host'] = args.host if args.base_path is not None: spec['basePath'] = args.base_path if args.version is not None: spec['info']['version'] = args.version if args.as_markdown: if args.out_dir is None: print swagger_json_to_markdown(spec) else: out_file_name = args.out_file_name if args.out_file_name else "swagger.md" with open("{}/{}".format(args.out_dir, out_file_name), 'w') as f: f.write(swagger_json_to_markdown(spec)) f.close else: if args.out_dir is None: print(json.dumps(spec, indent=4)) else: out_file_name = args.out_file_name if args.out_file_name else "swagger.json" with open("{}/{}".format(args.out_dir, out_file_name), 'w') as f: f.write(json.dumps(spec, indent=4)) f.close()
def get(self): swag = swagger(app) swag['info']['version'] = "2.0" swag['info']['title'] = "Suppression Export API" for path, methods in swag['paths'].items(): for method, info in methods.items(): if "401" in info['responses'].keys(): info['responses']["401"] = { "description": "User is not authenticated" } if "400" in info['responses'].keys(): info['responses']["401"] = { "description": "Request body was malformed" } if "404" in info['responses'].keys(): info['responses']["404"] = { "description": "Resource could not be found" } return jsonify(swag)
def validate_closure(): """redefine QuestionnaireResponse.validate_document for efficient loop""" swag = swagger(current_app) draft4_schema = { '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'object', 'definitions': swag['definitions'], } validation_schema = 'QuestionnaireResponse' # Copy desired schema (to validate against) to outermost dict draft4_schema.update(swag['definitions'][validation_schema]) def validate(document, display_stack=False): try: jsonschema.validate(document, draft4_schema) return True except jsonschema.ValidationError as e: if display_stack: log.error(str(e)) return False return validate
def test_assessments_bundle(self): swagger_spec = swagger(self.app) example_data = swagger_spec['definitions']['QuestionnaireResponse'][ 'example'] instrument_id = example_data['questionnaire']['reference'].split('/')[ -1] self.login() self.bless_with_basics() self.promote_user(role_name=ROLE.STAFF.value) upload = self.client.post( '/api/patient/{}/assessment'.format(TEST_USER_ID), json=example_data) assert upload.status_code == 200 response = self.client.get( '/api/patient/assessment', query_string={'instrument_id': instrument_id}) response = response.json assert response['total'] == len(response['entry']) assert (response['entry'][0]['questionnaire']['reference'].endswith( instrument_id))
def spec(): swag = swagger(app) swag['info']['version'] = "0" swag['info']['title'] = "Datalake API" swag['info']['description'] = 'Query files in the datalake archive' return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = get_version() swag['info']['title'] = Metadata.TITLE swag['info']['description'] = Metadata.DESCRIPTION return jsonify(swag)
def microsoft_core_specification_swagger(*args, **kwargs): r""" Returns the API specification in the Swagger 2.0 (OpenAPI) JSON format. The Swagger API specification (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md) provides a standardized method to export REST API documentation and examples. Our documentation is built on-demand with the help of the Python package flask-swagger (https://github.com/gangverk/flask-swagger). The API specification includes GET, POST, PUT, and DELETE methods and Model definitions. --- definitions: - schema: id: Image description: An Image is a semantic construct that represents an uploaded image. Images can be uploaded for later processing or be used immediately for detection. Object detection will create Annotation models, which have a required Image parent. An Image can have multiple detections (i.e. Annotation models). required: - uuid properties: uuid: description: a deterministically-derived UUID based on the image pixels, which can be used to identify duplicate Images. type: string format: uuid - schema: id: Annotation description: An Annotation is a semantic construct that represents a *committed* detection, with a bounding box and species classification assigned as stored attributes. An Annotation is required to have a parent Image. All bounding box coordinates are relative to the size of the parent Image that was uploaded. required: - uuid - bbox properties: uuid: description: a deterministically-derived UUID based on the parent image's UUID and the bounding box coordinate (xtl, ytl, width, height) and orientation (theta), which can be used to identify duplicate Annotations. type: string format: uuid bbox: description: a 4-tuple of coordinates that defines a rectangle in the format (x-axis top left corner, y-axis top left corner, width, height) in pixels. These values are expected to be bounded by the size of the parent image. type: array theta: description: a rotation around the center of the annotation, in radians type: number species: description: a user-defined string to specify the species of the annotation (e.g. 'zebra' or 'massai_giraffe'). This value is used to filter matches and run-time models for ID. type: string viewpoint: description: a user-defined string to specify the viewpoint of the annotation (e.g. 'right' or 'front_left'). This value is used to filter matches and run-time models for ID. type: string name: description: the name of the individual format: uuid type: string - schema: id: Detection description: A Detection is a semantic constrict that represents an *un-committed* detection. A Detection can be committed to an Annotation to be stored permanently on the parent Image. required: - _image - score - bbox - xtl - ytl - xbr - ybr - width - height - theta - label properties: image: description: The Image that this Detection was found in $ref: "#/definitions/Image" score: description: The detection's classification score type: integer format: int32 bbox: description: The bounding box for this annotation, represented in the format (xtl, ytl, width, height) type: array items: type: number format: float xtl: description: The pixel coordinate for the top-left corner along the x-axis (xtl = x-axis top left) for the bounding box type: integer format: int32 ytl: description: The pixel coordinate for the top-left corner along the y-axis (ytl = y-axis top left) for the bounding box type: integer format: int32 xbr: description: The pixel coordinate for the bottom-right corner along the x-axis (ytl = x-axis bottom right) for the bounding box type: integer format: int32 ybr: description: The pixel coordinate for the bottom-right corner along the y-axis (ytl = y-axis bottom right) for the bounding box type: integer format: int32 width: description: The pixel width for the bounding box type: integer format: int32 height: description: The pixel height for the bounding box type: integer format: int32 theta: description: The rotation of the bounding box around its center, represented in radians type: number format: float species: description: The semantic species classification (class label) of the bounding box type: string viewpoint: description: The semantic viewpoint classification (class label) of the bounding box type: string - schema: id: Name description: A Name is the identification label for a group of Annotations required: - uuid - alias properties: uuid: description: a deterministically-derived UUID based on the image pixels, which can be used to identify duplicate Images. type: string format: uuid alias: description: a string alias for this individual, helpful for user-facing interfaces type: string - schema: id: Task description: A Task is a semantic construct that represents a background task (i.e. detection) in an asynchronous call. A Task has an optional callback on completion or the status (and result) can be checked via the API required: - uuid properties: uuid: description: a random UUID to identify a given asynchronous call, used to check status and results of a background task type: string format: uuid produces: - application/json responses: 200: description: Returns the Swagger 2.0 JSON format """ try: swag = swagger(current_app) except Exception: logger.info(str(traceback.format_exc())) # ut.embed() swag['info']['title'] = 'Wild Me - IA (Image Analysis)' swag['info'][ 'description' ] = 'Documentation for all classification, detection, and identification calls provided by Wild Me for the AI for Earth (AI4E) collaboration' swag['info']['version'] = 'v0.1' swag['info']['contact'] = { 'name': 'Wild Me Developers (AI4E)', 'url': 'http://wildme.org', 'email': '*****@*****.**', } swag['info']['license'] = { 'name': 'Apache 2.0', 'url': 'http://www.apache.org/licenses/LICENSE-2.0.html', } swag['host'] = 'demo.wildbook.org:5010' swag['schemes'] = [ 'http', ] # swag['basePath'] = PREFIX # "securityDefinitions": { # "apiKeyHeader": { # "type": "apiKey", # "name": "Ocp-Apim-Subscription-Key", # "in": "header" # }, # "apiKeyQuery": { # "type": "apiKey", # "name": "subscription-key", # "in": "query" # } # }, # "security": [ # { # "apiKeyHeader": [] # }, # { # "apiKeyQuery": [] # } # ], response = jsonify(swag) return response
def spec(): swag = swagger(current_app) swag['info']['version'] = "1.0" swag['info']['title'] = "LostAndFound" return jsonify(swag)
def spec(): swag = swagger(app, from_file_keyword='swagger_from_file') swag['info']['version'] = "1.0" swag['info']['title'] = "Tasks Provider API" return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "Neurosynth API" return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = "1.0.0" swag['info']['title'] = "Swagger Monkey API" return jsonify(swag)
def spec(): return jsonify(swagger(app))
def swagger_spec(): swag = swagger(current_app) # See http://swagger.io/specification/ for more information swag['basePath'] = current_app.config['SWAGGER_BASE_PATH'] swag['info']['title'] = "Digiez Assessment API" return jsonify(swag)
def swaggerController(): swag = swagger(app) swag["info"]["version"] = config.APP_VERSION swag["info"]["title"] = config.API_NAME return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "Files API" swag['basePath'] = "/" return jsonify(swag)
def spec(): swag = swagger(app) swag["info"]["version"] = get_version() swag["info"]["title"] = Metadata.TITLE swag["info"]["description"] = Metadata.DESCRIPTION return jsonify(swag)
def create_app(args): if not args.offline: from app.init import boot boot() from app.language import languages app = Flask(__name__) # For faster access language_map = {} for l in languages: language_map[l.code] = l.name if args.debug: app.config['TEMPLATES_AUTO_RELOAD'] = True # Map userdefined frontend languages to argos language object. if args.frontend_language_source == "auto": frontend_argos_language_source = type('obj', (object, ), { 'code': 'auto', 'name': 'Auto Detect' }) else: frontend_argos_language_source = next( iter([ l for l in languages if l.code == args.frontend_language_source ]), None) frontend_argos_language_target = next( iter([l for l in languages if l.code == args.frontend_language_target]), None) # Raise AttributeError to prevent app startup if user input is not valid. if frontend_argos_language_source is None: raise AttributeError( f"{args.frontend_language_source} as frontend source language is not supported." ) if frontend_argos_language_target is None: raise AttributeError( f"{args.frontend_language_target} as frontend target language is not supported." ) if args.req_limit > 0 or args.api_keys: from flask_limiter import Limiter limiter = Limiter(app, key_func=get_remote_address, default_limits=get_routes_limits( args.req_limit, Database() if args.api_keys else None)) else: from .no_limiter import Limiter limiter = Limiter() @app.errorhandler(400) def invalid_api(e): return jsonify({"error": str(e.description)}), 400 @app.errorhandler(500) def server_error(e): return jsonify({"error": str(e.description)}), 500 @app.errorhandler(429) def slow_down_error(e): return jsonify({"error": "Slowdown: " + str(e.description)}), 429 @app.route("/") @limiter.exempt def index(): return render_template('index.html', gaId=args.ga_id, frontendTimeout=args.frontend_timeout, offline=args.offline, api_keys=args.api_keys, web_version=os.environ.get('LT_WEB') is not None) @app.route("/languages", methods=['GET', 'POST']) @limiter.exempt def langs(): """ Retrieve list of supported languages --- tags: - translate responses: 200: description: List of languages schema: id: languages type: array items: type: object properties: code: type: string description: Language code name: type: string description: Human-readable language name (in English) 429: description: Slow down schema: id: error-slow-down type: object properties: error: type: string description: Reason for slow down """ return jsonify([{'code': l.code, 'name': l.name} for l in languages]) # Add cors @app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', "Authorization, Content-Type") response.headers.add('Access-Control-Expose-Headers', "Authorization") response.headers.add('Access-Control-Allow-Methods', "GET, POST") response.headers.add('Access-Control-Allow-Credentials', "true") response.headers.add('Access-Control-Max-Age', 60 * 60 * 24 * 20) return response @app.route("/translate", methods=['POST']) def translate(): """ Translate text from a language to another --- tags: - translate parameters: - in: formData name: q schema: oneOf: - type: string example: Hello world! - type: array example: ['Hello world!'] required: true description: Text(s) to translate - in: formData name: source schema: type: string example: en required: true description: Source language code - in: formData name: target schema: type: string example: es required: true description: Target language code - in: formData name: api_key schema: type: string example: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx required: false description: API key responses: 200: description: Translated text schema: id: translate type: object properties: translatedText: oneOf: - type: string - type: array description: Translated text(s) 400: description: Invalid request schema: id: error-response type: object properties: error: type: string description: Error message 500: description: Translation error schema: id: error-response type: object properties: error: type: string description: Error message 429: description: Slow down schema: id: error-slow-down type: object properties: error: type: string description: Reason for slow down """ if request.is_json: json = get_json_dict(request) q = json.get('q') source_lang = json.get('source') target_lang = json.get('target') else: q = request.values.get("q") source_lang = request.values.get("source") target_lang = request.values.get("target") if not q: abort(400, description="Invalid request: missing q parameter") if not source_lang: abort(400, description="Invalid request: missing source parameter") if not target_lang: abort(400, description="Invalid request: missing target parameter") batch = isinstance(q, list) if batch and args.batch_limit != -1: batch_size = len(q) if args.batch_limit < batch_size: abort(400, description= "Invalid request: Request (%d) exceeds text limit (%d)" % (batch_size, args.batch_limit)) if args.char_limit != -1: if batch: chars = sum([len(text) for text in q]) else: chars = len(q) if args.char_limit < chars: abort( 400, description= "Invalid request: Request (%d) exceeds character limit (%d)" % (chars, args.char_limit)) if source_lang == 'auto': candidate_langs = list( filter(lambda l: l.lang in language_map, detect_langs(q))) if len(candidate_langs) > 0: candidate_langs.sort(key=lambda l: l.prob, reverse=True) if args.debug: print(candidate_langs) source_lang = next( iter([ l.code for l in languages if l.code == candidate_langs[0].lang ]), None) if not source_lang: source_lang = 'en' else: source_lang = 'en' if args.debug: print("Auto detected: %s" % source_lang) src_lang = next(iter([l for l in languages if l.code == source_lang]), None) tgt_lang = next(iter([l for l in languages if l.code == target_lang]), None) if src_lang is None: abort(400, description="%s is not supported" % source_lang) if tgt_lang is None: abort(400, description="%s is not supported" % target_lang) translator = src_lang.get_translation(tgt_lang) try: if batch: return jsonify({ "translatedText": [translator.translate(text) for text in q] }) else: return jsonify({"translatedText": translator.translate(q)}) except Exception as e: abort(500, description="Cannot translate text: %s" % str(e)) @app.route("/detect", methods=['POST']) def detect(): """ Detect the language of a single text --- tags: - translate parameters: - in: formData name: q schema: type: string example: Hello world! required: true description: Text to detect - in: formData name: api_key schema: type: string example: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx required: false description: API key responses: 200: description: Detections schema: id: detections type: array items: type: object properties: confidence: type: number format: float minimum: 0 maximum: 1 description: Confidence value example: 0.6 language: type: string description: Language code example: en 400: description: Invalid request schema: id: error-response type: object properties: error: type: string description: Error message 500: description: Detection error schema: id: error-response type: object properties: error: type: string description: Error message 429: description: Slow down schema: id: error-slow-down type: object properties: error: type: string description: Reason for slow down """ if request.is_json: json = get_json_dict(request) q = json.get('q') else: q = request.values.get("q") if not q: abort(400, description="Invalid request: missing q parameter") candidate_langs = list( filter(lambda l: l.lang in language_map, detect_langs(q))) candidate_langs.sort(key=lambda l: l.prob, reverse=True) return jsonify([{ 'confidence': l.prob, 'language': l.lang } for l in candidate_langs]) @app.route("/frontend/settings") @limiter.exempt def frontend_settings(): """ Retrieve frontend specific settings --- tags: - frontend responses: 200: description: frontend settings schema: id: frontend-settings type: object properties: charLimit: type: integer description: Character input limit for this language (-1 indicates no limit) frontendTimeout: type: integer description: Frontend translation timeout language: type: object properties: source: type: object properties: code: type: string description: Language code name: type: string description: Human-readable language name (in English) target: type: object properties: code: type: string description: Language code name: type: string description: Human-readable language name (in English) """ return jsonify({ 'charLimit': args.char_limit, 'frontendTimeout': args.frontend_timeout, 'language': { 'source': { 'code': frontend_argos_language_source.code, 'name': frontend_argos_language_source.name }, 'target': { 'code': frontend_argos_language_target.code, 'name': frontend_argos_language_target.name } } }) swag = swagger(app) swag['info']['version'] = "1.2" swag['info']['title'] = "LibreTranslate" @app.route("/spec") @limiter.exempt def spec(): return jsonify(swag) SWAGGER_URL = '/docs' # URL for exposing Swagger UI (without trailing '/') API_URL = '/spec' # Call factory function to create our blueprint swaggerui_blueprint = get_swaggerui_blueprint(SWAGGER_URL, API_URL) app.register_blueprint(swaggerui_blueprint) return app
def spec(): swag = swagger(application) swag['info']['version'] = "1.0" swag['info']['title'] = "Fruit Store API" return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "Metabolitics API" return jsonify(swag)
def spec(): """generate swagger friendly docs from code and comments View function to generate swagger formatted JSON for API documentation. Pulls in a few high level values from the package data (see setup.py) and via flask-swagger, makes use of any yaml comment syntax found in application docstrings. Point Swagger-UI to this view for rendering """ swag = swagger(current_app) metadata = current_app.config.metadata swag.update({ "info": { "version": metadata['version'], "title": metadata['summary'], "termsOfService": metadata['home-page'], "contact": { "name": metadata['author'], "email": metadata['author-email'], "url": metadata['home-page'], }, }, "schemes": ("http", "https"), }) # Todo: figure out why description isn't always set if metadata.get('description'): swag["info"]["description"] = metadata.get('description').strip() # Fix swagger docs for paths with duplicate operationIds # Dict of offending routes (path and method), grouped by operationId operations = {} for path, path_options in swag['paths'].items(): for method, route in path_options.items(): if 'operationId' not in route: continue operation_id = route['operationId'] operations.setdefault(operation_id, []) operations[operation_id].append({'path': path, 'method': method}) # Alter route-specific swagger info (using operations dict) to prevent # non-unique operationId for operation_id, routes in operations.items(): if len(routes) == 1: continue for route_info in routes: path = route_info['path'] method = route_info['method'] route = swag['paths'][path][method] parameters = [] # Remove swagger path parameters from routes where it is optional for parameter in route.pop('parameters', ()): if parameter['in'] == 'path' and ( "{%s}" % parameter['name']) not in path: # Prevent duplicate operationIds by adding suffix # Assume "simple" version of API route if path parameter included but not in path swag['paths'][path][method][ 'operationId'] = "{}-simple".format(operation_id) continue parameters.append(parameter) # Overwrite old parameter list if parameters: swag['paths'][path][method]['parameters'] = parameters # Add method as suffix to prevent duplicate operationIds on synonymous routes if method == 'put' or method == 'post': swag['paths'][path][method]['operationId'] = "{}-{}".format( operation_id, method) return jsonify(swag)
def spec(): swag = swagger(app, prefix="/api") swag["info"]["base"] = "http://localhost:5000" swag["info"]["version"] = "1.0" swag["info"]["title"] = "Flask Author DB" return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = VERSION swag['info']['title'] = "AWS Resources Dashboard" return jsonify(swag)
def spec(): swag = swagger(app, prefix='/api') swag['info']['base'] = "http://localhost:5000" swag['info']['version'] = "1.0" swag['info']['title'] = "Sample API DB" return jsonify(swag)
def GetBooks(): result = BookService.GetBooks() return jsonify(swagger(result)), 200
def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "Ocean-provider" return jsonify(swag)
def spec(): """stub for swagger end points""" return jsonify(swagger(server))
def spec(): swag = swagger(app) swag['info']['version'] = "1.0" swag['info']['title'] = "HttpServer REST API" return jsonify(swag)
def get(self): swag = swagger(app) swag['info']['version'] = "1.0.0" swag['info']['title'] = "Mapeathor" return jsonify(swag)
def swaggerController(): # Spec file for marshmallow swag = swagger(app) swag['info']['version'] = config.APP_VERSION swag['info']['title'] = config.API_NAME return jsonify(swag)
def spec(): swag = swagger(app, from_file_keyword='swagger_from_file') swag['info']['version'] = get_version() swag['info']['title'] = Metadata.TITLE swag['info']['description'] = Metadata.DESCRIPTION return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = "multiple" swag['info']['title'] = APP_NAME swag['info']['description'] = APP_DESCRIPTION return jsonify(swag)
def spec(): """generate swagger friendly docs from code and comments View function to generate swagger formatted JSON for API documentation. Pulls in a few high level values from the package data (see setup.py) and via flask-swagger, makes use of any yaml comment syntax found in application docstrings. Point Swagger-UI to this view for rendering """ swag = swagger(current_app) metadata = current_app.config.metadata swag.update({ "info": { "version": metadata['version'], "title": metadata['summary'], "termsOfService": metadata['home-page'], "contact": { "name": metadata['author'], "email": metadata['author-email'], "url": metadata['home-page'], }, }, "schemes": (current_app.config['PREFERRED_URL_SCHEME'],), "securityDefinitions": { "ServiceToken": { "type": "apiKey", "name": "Authorization", "in": "header", }, "OAuth2AuthzFlow": { "type": "oauth2", "authorizationUrl": url_for('auth.authorize', _external=True), "tokenUrl": url_for('auth.access_token', _external=True), "flow": "accessCode", "scopes": {}, } }, }) # Todo: figure out why description isn't always set if metadata.get('description'): swag["info"]["description"] = metadata.get('description').strip() # Fix swagger docs for paths with duplicate operationIds # Dict of offending routes (path and method), grouped by operationId operations = {} for path, path_options in swag['paths'].items(): for method, route in path_options.items(): if 'operationId' not in route: continue operation_id = route['operationId'] operations.setdefault(operation_id, []) operations[operation_id].append({'path': path, 'method': method}) # Alter route-specific swagger info (using operations dict) to prevent # non-unique operationId for operation_id, routes in operations.items(): if len(routes) == 1: continue for route_info in routes: path = route_info['path'] method = route_info['method'] route = swag['paths'][path][method] parameters = [] # Remove swagger path parameters from routes where it is optional for parameter in route.pop('parameters', ()): if parameter['in'] == 'path' and ( "{%s}" % parameter['name']) not in path: # Prevent duplicate operationIds by adding suffix # Assume "simple" version of API route if path parameter # included but not in path swag['paths'][path][method][ 'operationId'] = "{}-simple".format(operation_id) continue parameters.append(parameter) # Overwrite old parameter list if parameters: swag['paths'][path][method]['parameters'] = parameters # Add method as suffix to prevent duplicate operationIds on # synonymous routes if method == 'put' or method == 'post': swag['paths'][path][method]['operationId'] = "{}-{}".format( operation_id, method) return jsonify(swag)
def spec(): swag = swagger(app) swag['info']['version'] = '1.0' swag['info']['title'] = 'NeCSuS API' return jsonify(swag)
from flask import Flask, request import flask_swagger from server.model_utils import load_models, int_to_label_dict app = Flask('Text_Classification_Server') flask_swagger.swagger(app) models = load_models('/models/') @app.route('/list_models', methods=['GET']) def list_models(): formatted_models = [{ 'id': i, 'model': model.__repr__() } for i, model in enumerate(models)] return {'models': formatted_models} @app.route('/predict/<id>', methods=['POST']) def predict(id): assert request.method == 'POST', 'Only POST-call allowed at this endpoint' form = request.form texts = [] for key in form.keys(): for value in form.getlist(key): if key == 'text': texts.append(value) texts = texts if type(texts) == list else [texts] values = models[int(id)].predict(texts) labels = [int_to_label_dict[value] for value in values]
def spec(): swag = swagger(app) swag['info']['version'] = "0.0.7" swag['info']['title'] = "Prometheus REST API" return jsonify(swag)