Created
March 14, 2021 07:08
-
-
Save wfng92/8d459df8d60fe72c3e2b21a3458defa1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import FastAPI | |
from fastapi.openapi.utils import get_openapi | |
import os | |
app = FastAPI() | |
lable_lang_mapping = {"Plain JS": "JavaScript", "NodeJS": "JavaScript"} | |
@app.get("/hello") | |
async def hello(): | |
return [{"message": "hello"}] | |
@app.get("/world") | |
async def world(): | |
return [{"message": "world"}] | |
def add_examples(openapi_schema: dict, docs_dir): | |
path_key = 'paths' | |
code_key = 'x-codeSamples' | |
for folder in os.listdir(docs_dir): | |
base_path = os.path.join(docs_dir, folder) | |
files = [f for f in os.listdir(base_path) if os.path.isfile(os.path.join(base_path, f))] | |
for f in files: | |
parts = f.split('-') | |
if len(parts) >= 2: | |
route = '/' + '/'.join(parts[:-1]) | |
method = parts[-1].split('.')[0] | |
print(f'[{path_key}][{route}][{method}][{code_key}]') | |
if route in openapi_schema[path_key]: | |
if code_key not in openapi_schema[path_key][route][method]: | |
openapi_schema[path_key][route][method].update({code_key: []}) | |
openapi_schema[path_key][route][method][code_key].append({ | |
'lang': lable_lang_mapping[folder], | |
'source': open(os.path.join(base_path, f), "r").read(), | |
'label': folder, | |
}) | |
else: | |
print(f'Error in adding examples code to openapi {f}') | |
return openapi_schema | |
def custom_openapi(): | |
if app.openapi_schema: | |
return app.openapi_schema | |
openapi_schema = get_openapi( | |
title="Custom title", | |
version="2.5.0", | |
description="This is a very custom OpenAPI schema", | |
routes=app.routes, | |
) | |
openapi_schema["info"]["x-logo"] = { | |
"url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" | |
} | |
app.openapi_schema = add_examples(openapi_schema, 'docs') | |
return app.openapi_schema | |
app.openapi = custom_openapi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment