[PYTHON] Get swagger.json with Flask-RESTX (Flask-RESTPlus) without starting the server

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

Get swagger.json with Flask-RESTX (Flask-RESTPlus) without starting the server
System trade starting with Python3: Get the latest program code
Get the weather with Python requests
Get the weather with Python requests 2
Get the width of the div on the server side with Selenium + PhantomJS + Python
Install the python module with pip on a server without root privileges
[Python] Get the variable name with str
Get started with the documentation tool Sphinx
Get holidays with the Google Calendar API
Log in to the remote server with SSH
[Python] Get the files in a folder with Python
The easiest way to get started with Django
Get the latest AMI information with the AWS CLI
Drawing tips with matplotlib on the server side
Get the latest AMI information with the AWS CLI
Get swagger.json with Flask-RESTX (Flask-RESTPlus) without starting the server
Get the id of a GPU with low memory usage
[Python x Zapier] Get alert information and notify with Slack
Get information with zabbix api
Get Alembic information with Python
PhytoMine-I tried to get the genetic information of plants with Python
Get the latest Linux kernel version with Arch Linux
GRPC starting with Go server and Dart client
[CGI] Run the Python program on the server with Vue.js + axios and get the output data
How to start the code written in Atom with one command without starting teminal