0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FlaskでSwaggerを設定する方法について

Posted at

はじめに

FlaskでSwaggerを使えるように設定する方法について説明したいと思います

前提

  • Flaskのプロジェクトを作成済み

flask-swagger-uiのインストール

flask-swagger-uiをインストールすることで使用できるようになります

pip install flask-swagger-ui

ディレクトリ構成

今回はmain.py、swagger.ymlを作成します

.
└── application
    ├── main.py
    ├── poetry.lock
    ├── pyproject.toml
    └── static
        └── swagger.yml

main.py

SWAGGER_URLにswaggerへアクセスする際のパス、API_URLにswagger.ymlのパスを記載します
get_swaggerui_blueprintを使ってSwagger用のBlueprintを取得し、SWAGGER_URLとAPI_URLを上書きした後にSwagger用のBlueprintをアプリケーションに登録します

main.py
from flask_swagger_ui import get_swaggerui_blueprint

app = Flask(__name__)

SWAGGER_URL = "/api/docs"
API_URL = "/static/swagger.yml"

# Call factory function to create our blueprint
swaggerui_blueprint = get_swaggerui_blueprint(
    SWAGGER_URL,
    API_URL,
)

app.register_blueprint(swaggerui_blueprint)


@app.route("/api/health")
def health():
    return {"msg": "pass"}

APIのドキュメントが記載されたymlファイル

swagger.ymlにAPIのドキュメントを記載します
今回はヘルスチェック用のAPIについて記載してます

static/swagger.yml
# https://swagger.io/specification/
openapi: "3.0.0"
# APIに関するメタデータ
info:
  title: project
  description: |-
    # プロジェクトの詳細
  version: 1.0.0

tags:
  - name: health
    description: ヘルスチェックAPI

paths:
  /api/health:
    get:
      tags:
        - health
      summary: ヘルスチェックAPI
      description: APIサーバー単独でのヘルスチェック
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                type: object
                properties:
                  msg:
                    type: string
                    description: ステータス
                    example: pass

今回は8000ポートを使用します
http://127.0.0.1:8000/api/docs へアクセスした際にSwaggerが出たら成功です

スクリーンショット 2025-01-04 9.03.43.png

また、ymlファイルを下記のようにGitHub Pagesにアップロードできます

参考文献

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?