sanic-org / sanic-ext

Extended Sanic functionality
https://sanic.dev/en/plugins/sanic-ext/getting-started.html
MIT License
50 stars 34 forks source link

How to generate openapi specification without running the app? #187

Closed iamvishalkhare closed 1 year ago

iamvishalkhare commented 1 year ago

Need help/suggestion here. Use case - I am trying to use openapi.json file during CI pipeline execution. I need to upload it somewhere for further use. openapi.json file is generated at run time and served at http://0.0.0.0:8090/docs/openapi.json I can't run the app during CI pipeline execution due to other dependencies and it seems like a security issue as well.

Can someone please help here on how can I generate openapi.json file without actually running the app? @ahopkins

ahopkins commented 1 year ago

Wow, I am not sure this would be easy to do. Sure, it's Python so everything should be possible. But it will take quite a bit of hacking. You would need to instantiate your Sanic app, attach all your routes and blueprints, then attach the blueprint using the blueprint factory which has some startup time methods to build the spec, setup and finalize the router, and ultimate calling:

SpecificationBuilder().build(app).serialize()

Sanic is not really meant for offline usage, and the spec builder certainly not. To do this you are probably going to be calling a lot of lower level functions that are considered private and might break on new releases.

You are probably much better off running your app in CI with something like this:

from sanic_ext.extensions.openapi.builders import SpecificationBuilder
from ujson import dumps
from pathlib import Path

@app.after_server_start
async def build_spec(app):
    spec = SpecificationBuilder().build(app).serialize()
    Path("/some/location/spec.json").write_text(dumps(spec))
    app.stop()
iamvishalkhare commented 1 year ago

Thanks @ahopkins.. Life saver :)