4
2

More than 3 years have passed since last update.

Flask-RESTX (Flask-RESTPlus) で, サーバ起動せずに swagger.json を取得する

Last updated at Posted at 2020-08-07

Flask-RESTX でサーバ起動せずにAPIドキュメントである swagger.json を取得したい場面がありました.

はじめに, Flaskアプリケーションのサンプルコードを示します.

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

flask run で起動すると, http://127.0.0.1:5000/swagger.json へのアクセスで, swagger.json を取得できます.

しかし, この方法では swagger.json を得るために, デバッグサーバを起動する手間がかかってしまいます. CIなどを使って, 自動で swagger.json を取得して共有するなどしたいケースでやや難があります.

そこで次のようなスクリプトを用意して実行すると, Flaskサーバを立ち上げることなく, swagger.json を取り出すことができます.

import json
import sys
from app import create_app


app = create_app()
json.dump(
    app.test_client().get("/swagger.json").get_json(),
    sys.stdout,
)

Flaskに同梱されているテスト用クライアントを使っています.

このスクリプトでは標準出力にだしてますが, ファイルにリダイレクトするなりで, JSONファイルを取得できます.

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2