There was a scene where I wanted to get the API document swagger.json without starting the server in Flask-RESTX.
First, here is sample code for the Flask application.
from flask import Flask
from flask_restx import Api, Resource, fields
def create_app():
app = Flask(__name__)
api = Api(app)
@api.route("/sample")
class SampleResource(Resource):
@api.marshal_with(api.model("sample model", {
"name": fields.String,
"age": fields.Integer,
}))
def get(self):
raise NotImplementedError()
return app
If you start it with flask run
, you can get swagger.json by accessing http://127.0.0.1:5000/swagger.json.
However, this method takes time to start the debug server in order to obtain swagger.json. There is some difficulty in cases where you want to automatically acquire and share swagger.json using CI etc. ..
Therefore, if you prepare and execute the following script, you can retrieve swagger.json without starting the Flask server.
import json
import sys
from app import create_app
app = create_app()
json.dump(
app.test_client().get("/swagger.json").get_json(),
sys.stdout,
)
I'm using the test client that comes with Flask.
This script produces standard output, but you can get a JSON file by redirecting to a file.
Recommended Posts