def main(): import os import sys top_level_dir = os.path.join(os.path.realpath(os.path.dirname(__file__)), '..') sys.path.append(top_level_dir) from fastapi.openapi.utils import get_openapi import json from bot import DiscordBot from webserver.server import WebServer app = WebServer(discord_bot=DiscordBot(current_dir=top_level_dir, ), ).app file_path = os.path.join(top_level_dir, 'docs', 'openapi.json') with open(file_path, 'w') as f: json.dump( get_openapi( title=app.title, version=app.version, openapi_version=app.openapi_version, description=app.description, routes=app.routes, ), f)
def custom_openapi(openapi_prefix: str = ""): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="GFW DATA API", version="0.1.0", description="Use GFW DATA API to explore, manage and access data.", routes=app.routes, openapi_prefix=openapi_prefix, ) openapi_schema["tags"] = tags_metadata openapi_schema["info"]["x-logo"] = {"url": "/static/gfw-data-api.png"} openapi_schema["x-tagGroups"] = [ {"name": "Meta API", "tags": ["Datasets", "Versions", "Assets"]}, {"name": "Geostore API", "tags": ["Geostore"]}, {"name": "Feature API", "tags": ["Features"]}, {"name": "SQL API", "tags": ["Query"]}, {"name": "Task API", "tags": ["Tasks"]}, ] app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(): # Return "cached" API schema if app.openapi_schema: return app.openapi_schema # Generate OpenAPI Schema openapi_schema = get_openapi( title=settings.SERVER_NAME, version=f"{settings.VERSION}:{settings.BUILD}", description=settings.SERVER_DESCRIPTION, routes=app.routes, ) # Make fields that are not required nullable for name, component in openapi_schema["components"]["schemas"].items(): if ("required" in component and component["required"] and "properties" in component and component["properties"]): for f_name, field in component["properties"].items(): if f_name not in component["required"]: field["nullable"] = True # Update field component["properties"][f_name] = field # Update component openapi_schema["components"]["schemas"][name] = component # Save schema so it doesn't have to be generated every time app.openapi_schema = openapi_schema return app.openapi_schema
async def get_open_api_endpoint( current_user: User = Depends(get_current_active_user)): response = JSONResponse( get_openapi(title="FastAPI security test", version=1, routes=app.routes)) return response
def custom_openapi(): if APP.openapi_schema: return APP.openapi_schema openapi_schema = get_openapi( title=OPENAPI_TITLE, version=OPENAPI_API_VERSION, description=OPENAPI_DESCRIPTION, routes=APP.routes, ) openapi_schema["info"]["contact"] = {"email": OPENAPI_CONTACT} openapi_schema["host"] = OPENAPI_HOST openapi_schema["servers"] = [ {"url": OPENAPI_SERVER_URL, "basePath": OPENAPI_SERVER_BASEPATH} ] openapi_schema["externalDocs"] = { "description": OPENAPI_EXTERNALDOCS_DESC, "url": OPENAPI_EXTERNALDOCS_URL, } APP.openapi_schema = openapi_schema return APP.openapi_schema
def custom_openapi(): """Build custom OpenAPI schema.""" if APP.openapi_schema: return APP.openapi_schema extra_info_file = Path(__file__).parent / "openapi-info.yml" with open(extra_info_file) as stream: extra_info = yaml.load(stream, Loader=yaml.SafeLoader) openapi_schema = get_openapi( title=APP.title, description=APP.description, version=APP.version, servers=APP.servers, routes=APP.routes, tags=[{ "name": "translator", }, { "name": "reasoner", }], ) openapi_schema["info"].update(extra_info) APP.openapi_schema = openapi_schema return APP.openapi_schema
async def get_open_api_endpoint(api_key: APIKey = Depends(get_api_key)): response = JSONResponse( get_openapi(title=app.title, version=app.version, routes=app.routes, description=app.description)) return response
def custom_openapi(openapi_prefix: str): if app.openapi_schema: return app.openapi_schema revision = "0.1.0" try: revision = (subprocess.run( ["git", "rev-parse", "--short", "HEAD"], stdout=subprocess.PIPE, ).stdout.decode("utf-8").rstrip()) except Exception: pass openapi_schema = get_openapi( title="Ayase", version=revision, description="The Ayase Imageboard Archival Standard", routes=app.routes, openapi_prefix=openapi_prefix, ) openapi_schema["info"]["x-logo"] = { "url": "https://c4.wallpaperflare.com/wallpaper/530/77/135/anime-yotsuba-fuuka-ayase-mr-koiwai-yotsuba-wallpaper-preview.jpg" # "url": "https://c4.wallpaperflare.com/wallpaper/487/5/317/anime-yotsuba-fuuka-ayase-wallpaper-preview.jpg" } app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=defaults.SERVICE_NAME, version=defaults.VERSION, routes=app.routes ) try: openapi_schema["components"]["schemas"].pop("ValidationError") openapi_schema["components"]["schemas"]["HTTPValidationError"] = { "title": "ValidationError", "type": "object", "properties": { "code": {"type": "string"}, "reason": { "type": "object", "additionalProperties": {"type": "string"}, }, }, "required": ["code", "reason"], } except KeyError: # Do nothing pass app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Cast-MyVote API", version="v1.0.0", description= "A REST API to create Polls, cast votes on Polls, fetch Poll details, results.\n" "Built on top of Blockchain to providing full decentralization" "<h1>✨ Features</h1>" "<ul><li> 🗳️ Create polls with as many options you " "want, also set a name and limit for your " "poll.</li> " "<li> ⏲ Poll vote counting stops automatically when total no. of votes hits the poll limit.</li>" "<li> 📇 Fetch poll details</li>" "<li> 📥 Cast votes on a particular poll</li>" "<li> ⏲ Get live count of votes on a poll</li>" "<li> ▶️ Check if a poll is still active or not</li>" "<li> 📉 Get final results of a poll</li></ul>", routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://i.imgur.com/Abg3WeV.png" } app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(app): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Challenge Api Documentation", version="1.0.1", terms_of_service="http://example.com/terms/", description="Documentation for my custom OpenAPI schema", contact={ "name": "Jorge Cardona", "url": "https://github.com/JorgeCardona/AI", "email": "*****@*****.**", }, license_info={ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html", }, routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" } app.openapi_schema = openapi_schema return app.openapi_schema
async def get_openapi_json(workspace_id: str, request: Request, workspace_repo=Depends( get_repository(WorkspaceRepository))): global openapi_definitions if openapi_definitions[workspace_id] is None: openapi_definitions[workspace_id] = get_openapi( title=f"{config.PROJECT_NAME} - Workspace {workspace_id}", description=config.API_DESCRIPTION, version=config.VERSION, routes=workspace_router.routes, tags=workspace_tags_metadata) workspace = workspace_repo.get_workspace_by_id(workspace_id) scope = {get_scope(workspace): "List and Get TRE Workspaces"} openapi_definitions[workspace_id]['components']['securitySchemes'][ 'oauth2']['flows']['authorizationCode']['scopes'] = scope # Add an example into every workspace_id path parameter so users don't have to cut and paste them in. for route in openapi_definitions[workspace_id]['paths'].values(): for verb in route.values(): # We now have a list of parameters for each route for parameter in verb['parameters']: if (parameter['name'] == 'workspace_id'): parameter['schema']['example'] = workspace_id return openapi_definitions[workspace_id]
def openapi(self): if self._app.openapi_schema: return self._app.openapi_schema kwargs = dict( title=self._app.title, version=self._app.version, description=self._app.description, routes=self._app.routes, tags=self._app.openapi_tags, servers=self._app.servers, ) openapi_schema = get_openapi(**kwargs) for path in openapi_schema.get('paths', {}).values(): for http_method in path.values(): params = http_method.get('parameters') if params is not None: for i, p in enumerate(params): if p.get('name') == 'dataset_id': params.pop(i) self._app.openapi_schema = openapi_schema return self._app.openapi_schema
def custom_openapi(): """Customize openapi documentation page.""" if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="pollination.cloud", version="0.0.1", description="This page only documents %s endpoints." " See the link below for full API documentation." % PROJECT_NAME, routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://user-images.githubusercontent.com/2915573/53690998-7239bb00-3d43-11e9-85b1-d9ac9d140c0f.png" } openapi_schema["info"]["license"] = { "name": "AGPL", "url": "https://www.gnu.org/licenses/agpl-3.0.en.html" } openapi_schema["externalDocs"] = { "description": "Pollination Cloud full API documentation.", "url": "https://pollination.cloud/api" } # openapi_schema["servers"] = [{"url": "http://api.pollination.cloud"}] app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi() -> Dict[str, Any]: if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=app.title, version=app.version, description=app.description, routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://lh6.googleusercontent.com/x2UaZCMiAO_1jYhft4JcXq8aYBOikH67GA6oWABUEsQTESCpjDlqX8vr1XFdLwPG2xd8vhkNyIrbFfHUYRoDckBJ9RQmNdaVK6DC4lckHRheX8OfDMQdSSkKER2C_AgUSw=w1280" } # openapi_schema["info"]["termsOfService"] = "https://obsidion-dev.com/terms" openapi_schema["info"]["contact"] = { "name": "API Support", "email": "*****@*****.**", "url": "https://obsidion-dev.com", } openapi_schema["info"]["license"] = { "name": "GNU AGPL v3", "url": "https://www.gnu.org/licenses/agpl-3.0.html", } app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(): """ Customizes the openapi schema for our usage. """ if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=app.title, description=app.description, version=app.version, routes=app.routes, ) app.openapi_schema = openapi_schema paths_to_delete = { x for x in app.openapi_schema["paths"] if x.endswith("$") } for path in paths_to_delete: app.openapi_schema["paths"][ path[:-1]] = app.openapi_schema["paths"][path] del app.openapi_schema["paths"][path] openapi_schema["info"]["x-logo"] = {"url": assets_defaults.LOGO_URL} return app.openapi_schema
def custom_openapi(): """Generates schema from OpenFaas function particulars""" if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=handler.FUNCTION_NAME, version=f"v{handler.FUNCTION_VERSION}", routes=app.routes, ) paths = openapi_schema["paths"] upd_paths = {} # Supplement path specs for key in paths: path = paths[key] for method in path: path[method]["tags"] = ["Function Definitions"] # Modify path(s) to account for function being exposed # behind OpenFaas gateway rel_path = f"/function/{handler.FUNCTION_NAME}" if key.startswith(rel_path): upd_paths[key] = path else: rel_path = f"{rel_path}{key}" upd_paths[rel_path] = path openapi_schema["paths"] = upd_paths app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=title, version="1.0.0", description=open("./docs/description.md", "r").read(), routes=app.routes, ) openapi_schema["info"]["contact"] = { "name": "Serverless API Support", "url": "https://www.google.com/contact/", "email": "*****@*****.**", } openapi_schema["info"]["license"] = { "name": "Serverless", "url": "https://google.com/api/license/", } openapi_schema["info"]["termsOfService"] = "https://www.google.com/terms/" openapi_schema["info"]["x-logo"] = { "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" } openapi_schema["x-tagGroups"] = [{ "name": "API Calls", "tags": ["items", "custom"] }] app.openapi_schema = openapi_schema return app.openapi_schema
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=settings.APP_TITLE, version=settings.APP_VERSION, description=settings.APP_DESCRIPTION, routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" } # print ("openapi_schema : ...") # pp.pprint( openapi_schema.keys() ) # pp.pprint( openapi_schema ) # print ("\nopenapi_schema.info : ...") # pp.pprint( openapi_schema['info'] ) # print ("\nopenapi_schema.openapi : ...") # pp.pprint( openapi_schema['openapi'] ) # print ("\nopenapi_schema.openapi : ...") # pp.pprint( openapi_schema['components'] ) app.openapi_schema = openapi_schema return app.openapi_schema
def _custom_openapi(zelf: FastAPI) -> Dict: if not zelf.openapi_schema: openapi_schema = get_openapi( title=zelf.title, version=zelf.version, openapi_version=zelf.openapi_version, description=zelf.description, routes=zelf.routes, openapi_prefix=zelf.openapi_prefix, ) # ReDoc vendor extensions # SEE https://github.com/Redocly/redoc/blob/master/docs/redoc-vendor-extensions.md openapi_schema["info"]["x-logo"] = { "url": LOGO, "altText": "osparc-simcore logo", } # # TODO: load code samples add if function is contained in sample # TODO: See if openapi-cli does this already # openapi_schema["paths"]["/meta"]["get"]["x-code-samples"] = [ { "lang": "python", "source": "print('hello world')", }, ] zelf.openapi_schema = openapi_schema return zelf.openapi_schema
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="EPCIS Sanitisation Demonstration API", version="1.0.0", description="This is a Webservice to calculate " + "<a href='https://github.com/european-epc-competence-center/epcis-sanitisation'>sanitised EPCIS events</a>.", routes=app.routes, ) openapi_schema["info"]["x-logo"] = { "url": "https://eecc.info/img/eecc/logo_213x182.png" } openapi_schema["paths"]["/sanitise_xml_event/"]["post"]["requestBody"] = { "content": { "application/xml": { "schema": { "title": "XML EPCIS Document", "type": "string" } } }, "required": True } app.openapi_schema = openapi_schema return app.openapi_schema
def main(): if len(sys.argv) > 1: build = sys.argv[1] else: build = settings.BUILD if len(sys.argv) > 2: custom_url = sys.argv[2] else: custom_url = None base_path = Path("docs/api") if not base_path.exists() and Path("backend").exists(): os.makedirs(base_path) with open(base_path.joinpath("index.html"), "w") as html: html.write( get_redoc_html( openapi_url=custom_url if custom_url else app.openapi_url, title=app.title, ).body.decode("utf-8")) with open(base_path.joinpath("openapi.json"), "w") as j: j.write( json.dumps( get_openapi( title=settings.SERVER_NAME, version=f"{settings.VERSION}:{build}", description="PartyFiller API Specification", routes=app.routes, )))
async def get_open_api_endpoint(): return JSONResponse( get_openapi(title="Qanet Docs", servers=[{ "url": "/api/v1" }], version=1, routes=api_router.routes))
async def get_open_api_endpoint( _: fastapimsal.UserIdentity = Depends(user_authenticated), ) -> Union[JSONResponse, HTMLResponse]: """ Serves OpenAPI endpoints """ return JSONResponse( get_openapi(title="Example API", version="0.0.1", routes=app.routes))
async def get_open_api_endpoint(api_key: APIKey = Depends(get_api_key)): response = JSONResponse( get_openapi( title="DRAMA", version=__version__, description="https://github.com/benhid/drama", routes=app.routes, )) return response
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Radia Production API", description="Inkling Performance Labs Production API Service. <br>" "URL: https://github.com/IPLSplatoon/Radia-Productions | Documentation Licence: CC-BY 4.0", version="1.2.0", routes=app.routes, tags=[ { "name": "commentators", "description": "Retrieve and set details on commentators" }, { "name": "live", "description": "Retrieve on commentators currently live in a Discord Guild/Twitch Channel" }, { "name": "organisation", "description": "Retrieve information about a Discord Guild/Twitch Channel settings" }, { "name": "commands", "description": "Retrieve custom commands for a Discord Guild/Twitch Channel" }, { "name": "mocking", "description": "Used for mocking other endpoints in testing scenario. Does **not** support verify" "the header `Authorization` apiKey!" }, { "name": "seeding", "description": "A set of seeding tools." }, ]) security = openapi_schema["components"]["securitySchemes"] security["APIKeyHeader"]["description"] = "An API Authorization token must be provided to be able to use an " \ "endpoint. <br> To do this set you HEADER can be set as like the " \ "following. `Authorization: Your_Authorization_Key` " \ "<br> A Key can be issued by IPL Production Team." openapi_schema["info"]["x-logo"] = { "url": "https://store.iplabs.work/production.png", "href": "https://iplabs.work", "altText": "Inkling Performance Labs Productions" } app.openapi_schema = openapi_schema return app.openapi_schema
def construct_open_api_schema(app, trapi_version, prefix=""): plater_title = config.get('PLATER_TITLE', 'Plater API') plater_version = os.environ.get('PLATER_VERSION', '1.0.0') if app.openapi_schema: return app.openapi_schema open_api_schema = get_openapi( title=plater_title, version=plater_version, description='', routes=app.routes, ) open_api_extended_file_path = config.get_resource_path( f'../openapi-config.yaml') with open(open_api_extended_file_path) as open_api_file: open_api_extended_spec = yaml.load(open_api_file, Loader=yaml.SafeLoader) x_translator_extension = open_api_extended_spec.get("x-translator") contact_config = open_api_extended_spec.get("contact") terms_of_service = open_api_extended_spec.get("termsOfService") servers_conf = open_api_extended_spec.get("servers") tags = open_api_extended_spec.get("tags") title_override = (open_api_extended_spec.get("title") or plater_title) + f' (trapi v-{trapi_version})' description = open_api_extended_spec.get("description") if tags: open_api_schema['tags'] = tags if x_translator_extension: # if x_translator_team is defined amends schema with x_translator extension open_api_schema["info"]["x-translator"] = x_translator_extension open_api_schema["info"]["x-translator"][ "biolink-version"] = config.get("BL_VERSION", "1.5.0") if contact_config: open_api_schema["info"]["contact"] = contact_config if terms_of_service: open_api_schema["info"]["termsOfService"] = terms_of_service if description: open_api_schema["info"]["description"] = description if title_override: open_api_schema["info"]["title"] = title_override if servers_conf: for cnf in servers_conf: if prefix and 'url' in cnf: cnf['url'] = cnf['url'] + prefix open_api_schema["servers"] = servers_conf open_api_schema["info"]["x-trapi"] = {"version": trapi_version} return open_api_schema
async def get_open_api_endpoint(_api_key: APIKey = Depends( self._get_api_key())): response = JSONResponse( get_openapi( title=self.app.app_config.app_name, version=self.app.app_config.app_version, routes=self.server.routes, tags=self.app.app_config.tags_metadata, ), ) return response
def openapi(self) -> Dict: if not self.openapi_schema: self.openapi_schema = get_openapi( title=self.title, version=self.version, openapi_version=self.openapi_version, description=self.description, routes=self.routes, ) return self.openapi_schema
def custom_openapi(): if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title="Leaderboard API", version="", routes=app.routes, ) app.openapi_schema = openapi_schema return app.openapi_schema