ErikWittern / openapi-snippet

Generates code snippets for given Swagger / Open API documents
MIT License
116 stars 67 forks source link

Help on usage with redoc #40

Open bzon opened 4 years ago

bzon commented 4 years ago

I stumbled on this repository when trying to use redoc to generate static html public documentation.

Now, I'm trying to find out how to automate the generation of code samples. With an openapi.yaml file in hand, I do the following:

redoc-cli bundle openapi.yaml
thblckjkr commented 4 years ago

Maybe i'm late for solving the issue, but this could help for future searches.

The package oas3-api-snippet-enricher is a good wrapper to easily enrich the docs.

haviduck commented 3 years ago

i dont know which framework you use, but this approach is language agnostic: 1) start your api service 2) link an action to desired event, in my case, whenever a user visits my redoc page generated by fastapi. 3) dump spec to a json or yaml file 4) using enricher, run a shell exec (in my case) and save output to a publicly available directory/openapi.json 5r) make redoc read from that specific file

Fastapi code:

@app.get("/redoc", include_in_schema=False)
async def redoc_html():
    if os.path.exists("openapi.json"):
        os.remove("openapi.json")
    else:
        print("Can not delete the file as it doesn't exists")
    with open(f"openapi.json", "x") as fd:
        print(json.dumps(app.openapi()), file=fd)
        os.system("/mnt/d/projectdir/generated/node_modules/.bin/snippet-enricher-cli --targets='python_python3,node_request,shell_curl,php_curl,csharp_restsharp,python_requests,javascript_jquery,javascript_xhr' "
              "--input openapi.json > static/openapi.json")
    return get_redoc_html(
        openapi_url="/static/openapi.json",
        title=app.title + " - ReDoc",
        redoc_js_url="/static/redoc.standalone.js",
    )

if you use html + js:

<!DOCTYPE html>
<html>
  <head>
    <title>ReDoc</title>
    <!-- needed for adaptive design -->
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">

    <!--
    ReDoc doesn't change outer page styles
    -->
    <style>
      body {
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <redoc spec-url='/your/public/dir/openapi.json'></redoc>
    <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
  </body>
</html>