包括的で正確なAPIドキュメントの生成は、ソフトウェア開発において重要でありながら、しばしば退屈な作業です。OpenAPI Specification(以前はSwaggerとして知られていました)は、RESTful APIを定義するための業界標準として登場しました。これは、ソースコード、ドキュメント、またはネットワークトラフィックの検査にアクセスすることなく、人間とコンピューターの両方がサービスの機能を検出および理解できるようにする機械可読形式を提供します。1
多くのフレームワークがコードアノテーション(docstringsなど)からOpenAPI仕様を生成するプラグインを提供していますが、仕様の作成に対してより直接的でプログラムによる制御が必要となるシナリオがあります。これは、レガシーシステム、非標準フレームワークを扱っている場合、または複数のマイクロサービスで構成されるAPIの仕様を生成する必要がある場合などが考えられます。
ここでpyswagger
が登場します。これは、OpenAPIのツールキットとして機能する強力なPythonライブラリです。OpenAPI仕様で定義されたサービスを消費するためのAPIクライアントとしてよく使用されますが、その真の力は、仕様をプログラムで構築、操作、検証できるオブジェクトモデルにあります。
この包括的なチュートリアルでは、pyswagger
を使用して、Flaskで構築されたシンプルなPython Webアプリケーションの完全なOpenAPI 3.0仕様を手動で、しかし自動的に生成するプロセスを順を追って説明します。pyswagger
のオブジェクトがOpenAPI標準のコンポーネントにどのように直接マッピングされるかを示しながら、仕様をゼロから段階的に構築していきます。最終的には、生成されたopenapi.json
ファイルだけでなく、アプリケーションから直接提供されるライブのインタラクティブなドキュメントUIも手に入ります。
開発チームが最大限の生産性で協力するための統合されたオールインワンプラットフォームが必要ですか?
Apidogはあなたのすべての要求に応え、Postmanをはるかに手頃な価格で置き換えます!
パート1:プロジェクト環境のセットアップ
仕様の生成を開始する前に、適切な開発環境をセットアップする必要があります。これには、依存関係を管理するための分離されたPython環境の作成と、必要なライブラリのインストールが含まれます。
ワークスペースの作成 ⚙️
まず、プロジェクト用のディレクトリを作成しましょう。ターミナルまたはコマンドプロンプトを開き、以下のコマンドを実行します:Bash
# Create a new directory for our project
mkdir pyswagger-tutorial
cd pyswagger-tutorial
# Create a Python virtual environment
# On macOS/Linux
python3 -m venv venv
# On Windows
python -m venv venv
仮想環境は、Pythonのインストールと多数のサポートファイルを含む自己完結型のディレクトリツリーです。仮想環境を使用することで、このプロジェクトのためにインストールするパッケージが、他のプロジェクトのためにインストールされたパッケージと競合しないようにすることができます。
次に、仮想環境をアクティベートします:Bash
# On macOS/Linux
source venv/bin/activate
# On Windows
.\venv\Scripts\activate
アクティベートされると、ターミナルのプロンプトが仮想環境の名前(例:(venv)
)を表示するように変わり、その中で作業していることを示します。
必要なライブラリのインストール
環境がアクティブになったら、このチュートリアルで必要となるPythonライブラリをインストールできます。仕様を構築するためのpyswagger
自体、シンプルなWeb APIを作成するためのFlask
、そしてpyswagger
がYAML操作に使用するためPyYAML
が必要です:Bash
pip install "pyswagger[utils]" Flask PyYAML
pyswagger
をインストールする際の[utils]
部分は、生成された仕様の正確性を後でチェックするために使用するバリデーターのような役立つユーティリティが含まれているため、良い習慣です。
適切なプロジェクト管理のために、依存関係をrequirements.txt
ファイルに固定しておくのが賢明です:Bash
pip freeze > requirements.txt
これでrequirements.txt
にはライブラリとその特定のバージョンが含まれ、他の人があなたのプロジェクトを簡単に再現できるようになります。
基本的なFlaskアプリケーションの作成
さて、最小限のFlaskアプリケーションを作成しましょう。これは、ドキュメント化するAPIの基盤となります。
プロジェクトディレクトリに、app.py
という名前の新しいファイルを作成し、以下のコードを追加します:Python
# app.py
from flask import Flask, jsonify
# Initialize the Flask application
app = Flask(__name__)
@app.route("/")
def index():
""" A simple endpoint to check if the app is running. """
return jsonify({"message": "API is up and running!"})
if __name__ == "__main__":
# Runs the Flask app on http://127.0.0.1:5000
app.run(debug=True)
このコードは、単一のエンドポイントを持つ非常にシンプルなWebサーバーをセットアップします。これを実行するには、仮想環境がまだアクティブであることを確認し、ターミナルで以下のコマンドを実行します:Bash
python app.py
サーバーが実行されていることを示す出力が表示されるはずです。例えば以下のようになります:
* Serving Flask app 'app'
* Debug mode: on
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
これで、Webブラウザを開くか、curl
のようなツールを使用してhttp://127.0.0.1:5000
にアクセスできます。JSONレスポンス:{"message": "API is up and running!"}
が表示されるはずです。
基本的な環境とアプリケーションのスケルトンが整ったので、pyswagger
のコアコンセプトに入っていきましょう。
パート2:pyswagger
オブジェクトモデルの理解
pyswagger
を効果的に使用して仕様を生成するには、まずそのオブジェクトモデルがOpenAPIドキュメントの構造にどのように対応しているかを理解する必要があります。OpenAPI仕様は、基本的に特定のスキーマを持つ大きなJSONまたはYAMLオブジェクトです。pyswagger
は、このスキーマを反映するPythonクラスとオブジェクトを提供し、より直感的でオブジェクト指向的な方法で仕様を構築できるようにします。
OpenAPI 3.0仕様のコアコンセプト 📜
OpenAPI 3.0ドキュメントには、いくつかの主要なトップレベルフィールドがあります:
openapi
: OpenAPI Specificationのバージョンを指定する文字列(例:'3.0.0'
)。info
: APIに関するメタデータを提供するオブジェクト。これには、title
、version
、description
、および連絡先情報が含まれます。servers
: APIのベースURLを定義するサーバーオブジェクトの配列。paths
: 最も重要なフィールド。このオブジェクトは、利用可能なすべてのAPIエンドポイント(パス)と、それらに対して実行できるHTTP操作(GET、POST、PUT、DELETEなど)を保持します。components
: 仕様の異なる部分で再利用可能なオブジェクトのセットを保持するオブジェクト。これは、仕様をDRY(Don't Repeat Yourself)に保つための鍵です。再利用可能なschemas
(データモデル)、responses
、parameters
、examples
などを定義できます。
OpenAPIからpyswagger
オブジェクトへのマッピング
pyswagger
は、これらのOpenAPIの概念からPythonオブジェクトへのクリーンなマッピングを提供します。私たちが使用する主要なものを探ってみましょう。
pyswagger
の中心的なオブジェクトはApp
です。App
インスタンスをOpenAPIドキュメントのルートと考えることができます:Python
from pyswagger import App
# The root of the specification document
# We initialize it with a version, but it can also load from a URL or file
root_app = App(version='3.0.0')
App
オブジェクトを取得したら、OpenAPIフィールドに直接対応するその属性を埋め始めることができます。pyswagger
はビルダーパターンを使用しており、流暢で読みやすい構文を可能にします。
InfoとServers
info
とservers
セクションは簡単に埋めることができます:Python
# Populating the 'info' object
root_app.info.title = "User API"
root_app.info.version = "1.0.0"
root_app.info.description = "A simple API to manage users, used for the pyswagger tutorial."
# Populating the 'servers' array
# You create a Server object and append it
server = root_app.prepare_obj('Server', {'url': 'http://127.0.0.1:5000', 'description': 'Local development server'})
root_app.servers.append(server)
PathsとOperations
パスはApp
オブジェクトで定義されます。新しいパスを追加し、その中に操作(HTTPメソッド)を定義します。各操作は、summary
、description
、parameters
、requestBody
、およびresponses
のような詳細で構成されます:Python
# Defining a path and an operation
# This doesn't execute anything; it just builds the object structure.
path_item = root_app.define_path('/users')
get_op = path_item.define_op('get')
get_op.summary = "Retrieve a list of all users"
Components: Schemas、Parameters、およびResponses
構造化されたOpenAPI仕様の真の力は、再利用可能なコンポーネントから生まれます。「User」オブジェクトの構造が応答に現れるたびに定義する代わりに、components/schemas
で一度定義し、$ref
ポインターを使用して参照します。pyswagger
はこれをエレガントに処理します。
Schema
: Schema
オブジェクトはデータモデルを定義します。その型(object
、string
、integer
)とプロパティを指定できます:Python
# Preparing a Schema object for a User
user_schema = root_app.prepare_obj('Schema', {
'type': 'object',
'properties': {
'id': {'type': 'integer', 'format': 'int64'},
'username': {'type': 'string'},
'email': {'type': 'string', 'format': 'email'}
},
'required': ['id', 'username', 'email']
})
# Add it to the reusable components
root_app.components.schemas['User'] = user_schema
Parameter
: Parameter
オブジェクトは単一の操作パラメーターを定義します。その名前、場所(in
: 'path'
、'query'
、'header'
、または'cookie'
)、およびそのスキーマを指定します:Python
# Preparing a Parameter object for a user ID in the path
user_id_param = root_app.prepare_obj('Parameter', {
'name': 'user_id',
'in': 'path',
'description': 'ID of the user to retrieve',
'required': True,
'schema': {'type': 'integer'}
})
Response
: Response
オブジェクトは、特定のHTTPステータスコードに対する応答の構造を定義します。これには、description
とcontent
が含まれ、メディアタイプ(例:application/json
)とそのスキーマを指定します:Python
# Preparing a Response object for a 200 OK response returning a single user
# Note the use of '$ref' to point to our reusable User schema
ok_user_response = root_app.prepare_obj('Response', {
'description': 'Successful retrieval of a user',
'content': {
'application/json': {
'schema': {'$ref': '#/components/schemas/User'}
}
}
})
このマッピングを理解することが、仕様を構築するための鍵です。あなたは基本的に、pyswagger
が後で有効なOpenAPI JSONまたはYAMLファイルにシリアライズするPythonオブジェクトグラフを構築しています。
パート3:FlaskでシンプルなAPIを構築する
ドキュメント作成の演習を実践的にするために、ドキュメント化する実際のAPIが必要です。パート1のシンプルなFlaskアプリを拡張して、ユーザーリストを管理するための最小限のREST APIにします。このAPIは、pyswagger
で記述する「真実の源」として機能します。
シンプルな「ユーザー」APIの設計 📝
一般的なCRUD(作成、読み取り、更新、削除)操作を表す4つの基本的なエンドポイントを実装します:
GET /users
: すべてのユーザーのリストを取得します。POST /users
: 新しいユーザーを作成します。GET /users/{user_id}
: IDで単一のユーザーを取得します。DELETE /users/{user_id}
: IDでユーザーを削除します。
シンプルさのために、インメモリの「データベース」としてシンプルなPython辞書を使用します。実際のアプリケーションでは、これはPostgreSQLやMongoDBのようなデータベースへの接続になります。
Flaskエンドポイントの実装
これらのエンドポイントのロジックを含めるために、app.py
ファイルを更新しましょう。app.py
の内容を以下に置き換えます:Python
# app.py
from flask import Flask, jsonify, request, abort
app = Flask(__name__)
# --- In-Memory Database ---
# A simple dictionary to store our users.
# The key is the user_id (integer), and the value is the user data (dict).
USERS_DB = {
1: {"username": "alice", "email": "alice@example.com"},
2: {"username": "bob", "email": "bob@example.com"},
3: {"username": "charlie", "email": "charlie@example.com"},
}
# A counter to simulate auto-incrementing IDs for new users
LAST_INSERT_ID = 3
# --- API Endpoints ---
@app.route("/users", methods=["GET"])
def get_users():
""" Returns a list of all users. """
# We need to convert the dictionary to a list of user objects, including their IDs.
users_list = []
for user_id, user_data in USERS_DB.items():
user = {'id': user_id}
user.update(user_data)
users_list.append(user)
return jsonify(users_list)
@app.route("/users", methods=["POST"])
def create_user():
""" Creates a new user. """
global LAST_INSERT_ID
if not request.json or 'username' not in request.json or 'email' not in request.json:
abort(400, description="Missing username or email in request body.")
LAST_INSERT_ID += 1
new_user_id = LAST_INSERT_ID
new_user = {
"username": request.json["username"],
"email": request.json["email"],
}
USERS_DB[new_user_id] = new_user
# The response should include the ID of the newly created user
response_user = {'id': new_user_id}
response_user.update(new_user)
return jsonify(response_user), 201
@app.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
""" Returns a single user by their ID. """
if user_id not in USERS_DB:
abort(404, description=f"User with ID {user_id} not found.")
user_data = USERS_DB[user_id]
user = {'id': user_id}
user.update(user_data)
return jsonify(user)
@app.route("/users/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
""" Deletes a user by their ID. """
if user_id not in USERS_DB:
abort(404, description=f"User with ID {user_id} not found.")
del USERS_DB[user_id]
# A 204 No Content response is standard for successful deletions
return '', 204
if __name__ == "__main__":
app.run(debug=True, port=5000)
さて、python app.py
を再度実行すると、完全に機能する(ただしシンプルな)APIが手に入ります。curl
または同様のツールでテストできます:
- すべてのユーザーを取得:
curl http://127.0.0.1:5000/users
- 特定のユーザーを取得:
curl http://127.0.0.1:5000/users/1
- ユーザーを作成:
curl -X POST -H "Content-Type: application/json" -d '{"username": "david", "email": "david@example.com"}' http://127.0.0.1:5000/users
- ユーザーを削除:
curl -X DELETE http://127.0.0.1:5000/users/3
APIが実装されたので、ドキュメント作成の具体的なターゲットができました。次のステップは、pyswagger
を使用してこれらの各エンドポイントを詳細に記述することです。
パート4:pyswagger
でOpenAPI仕様を自動生成する
これが本チュートリアルの核心です。ここでは、pyswagger
をインポートし、そのオブジェクトモデルを使用してAPI構造を定義し、その構造を完全なopenapi.json
ファイルにシリアライズする別のPythonスクリプトを作成します。このアプローチは、仕様生成をアプリケーションロジックから分離するため、非常にクリーンで保守可能なパターンになり得ます。
仕様ジェネレーターの作成
プロジェクトディレクトリに、generate_spec.py
という名前の新しいファイルを作成します。このスクリプトは、OpenAPI仕様を構築および保存する役割を担います。
仕様を段階的に構築する
generate_spec.py
スクリプトを部分ごとに構築していきましょう。
1. インポートとApp
の初期化
まず、pyswagger
からApp
オブジェクトをインポートし、最終ファイルをダンプするのに役立つPyYAML
をインポートする必要があります。パート2で議論したように、ルートApp
オブジェクトを作成し、基本的なinfo
およびservers
セクションを埋めます:Python
# generate_spec.py
import json
from pyswagger import App
from pyswagger.contrib.client.requests import Client
# --- 1. Initialize the root App object ---
app = App(version='3.0.0')
# --- 2. Populating the Info & Servers sections ---
app.info.title = "User API"
app.info.version = "1.0.0"
app.info.description = "A simple API to manage users, for the pyswagger tutorial."
server = app.prepare_obj('Server', {
'url': 'http://127.0.0.1:5000',
'description': 'Local development server'
})
app.servers.append(server)
2. 再利用可能なコンポーネント(Schemas)の定義
優れたAPI設計は繰り返しを避けます。User
データモデルを一度定義し、それを再利用します。また、エラー応答(404 Not Foundなど)用の汎用的なError
スキーマも定義します。
generate_spec.py
に以下のコードを追加します:Python
# --- 3. Defining Reusable Components (Schemas) ---
# Schema for the Error response
error_schema = app.prepare_obj('Schema', {
'type': 'object',
'properties': {
'code': {'type': 'integer', 'format': 'int32'},
'message': {'type': 'string'}
}
})
app.components.schemas['Error'] = error_schema
# Schema for a single User. Note the properties match our USERS_DB structure.
user_schema = app.prepare_obj('Schema', {
'type': 'object',
'properties': {
'id': {
'type': 'integer',
'description': 'Unique identifier for the user.',
'readOnly': True # The client cannot set this value
},
'username': {
'type': 'string',
'description': 'The user\'s chosen username.'
},
'email': {
'type': 'string',
'description': 'The user\'s email address.',
'format': 'email'
}
},
'required': ['id', 'username', 'email']
})
app.components.schemas['User'] = user_schema
# Schema for creating a user (doesn't include the 'id' field)
new_user_schema = app.prepare_obj('Schema', {
'type': 'object',
'properties': {
'username': {
'type': 'string',
'description': 'The user\'s chosen username.'
},
'email': {
'type': 'string',
'description': 'The user\'s email address.',
'format': 'email'
}
},
'required': ['username', 'email']
})
app.components.schemas['NewUser'] = new_user_schema
3. /users
エンドポイントのドキュメント化
次に、/users
パスとその2つの操作:GET
とPOST
を定義します。
GET
の場合、応答はUser
オブジェクトの配列です。POST
の場合、リクエストボディはNewUser
オブジェクトを期待し、成功時の応答は単一のUser
オブジェクト(新しいIDを含む)になります。
Python
# --- 4. Documenting the Paths ---
# -- Path: /users --
path_users = app.define_path('/users')
# Operation: GET /users
op_get_users = path_users.define_op('get')
op_get_users.summary = "List all users"
op_get_users.description = "Returns a JSON array of all user objects."
op_get_users.tags.append('Users')
op_get_users.responses.A('200').description = "A list of users."
op_get_users.responses.A('200').content.A('application/json').schema.A(
'array', items={'$ref': '#/components/schemas/User'}
)
# Operation: POST /users
op_post_users = path_users.define_op('post')
op_post_users.summary = "Create a new user"
op_post_users.description = "Adds a new user to the database."
op_post_users.tags.append('Users')
op_post_users.requestBody.description = "User object that needs to be added."
op_post_users.requestBody.required = True
op_post_users.requestBody.content.A('application/json').schema.set_ref('#/components/schemas/NewUser')
op_post_users.responses.A('201').description = "User created successfully."
op_post_users.responses.A('201').content.A('application/json').schema.set_ref('#/components/schemas/User')
op_post_users.responses.A('400').description = "Invalid input provided."
op_post_users.responses.A('400').content.A('application/json').schema.set_ref('#/components/schemas/Error')
入れ子になったオブジェクト構造を構築するための、より簡潔な構文としてset_ref
とA
(「アクセス」を意味します)の使用に注目してください。
4. /users/{user_id}
エンドポイントのドキュメント化
次に、単一のユーザーと対話するためのパスをドキュメント化します。このパスには、パスパラメーター{user_id}
が含まれます。
GET
の場合、このパスパラメーターを定義する必要があります。応答は単一のUser
オブジェクトまたは404
エラーです。DELETE
の場合も、パスパラメーターが必要です。成功時の応答は204 No Content
です。
Python
# -- Path: /users/{user_id} --
path_user_id = app.define_path('/users/{user_id}')
# We can define the parameter once and reuse it for all operations on this path.
user_id_param = app.prepare_obj('Parameter', {
'name': 'user_id',
'in': 'path',
'description': 'ID of the user',
'required': True,
'schema': {'type': 'integer'}
})
path_user_id.parameters.append(user_id_param)
# Operation: GET /users/{user_id}
op_get_user_id = path_user_id.define_op('get')
op_get_user_id.summary = "Find user by ID"
op_get_user_id.description = "Returns a single user."
op_get_user_id.tags.append('Users')
op_get_user_id.responses.A('200').description = "Successful operation."
op_get_user_id.responses.A('200').content.A('application/json').schema.set_ref('#/components/schemas/User')
op_get_user_id.responses.A('404').description = "User not found."
op_get_user_id.responses.A('404').content.A('application/json').schema.set_ref('#/components/schemas/Error')
# Operation: DELETE /users/{user_id}
op_delete_user_id = path_user_id.define_op('delete')
op_delete_user_id.summary = "Deletes a user"
op_delete_user_id.description = "Deletes a single user from the database."
op_delete_user_id.tags.append('Users')
op_delete_user_id.responses.A('204').description = "User deleted successfully."
op_delete_user_id.responses.A('404').description = "User not found."
op_delete_user_id.responses.A('404').content.A('application/json').schema.set_ref('#/components/schemas/Error')
5. 仕様の検証と保存
最後に、最も満足のいくステップです。構築したオブジェクトグラフをOpenAPI 3.0スキーマに対してpyswagger
に検証させます。有効な場合は、JSONファイルにダンプします。
この最後のコードブロックをgenerate_spec.py
に追加します:Python
# --- 5. Validate and Save the Specification ---
if __name__ == '__main__':
try:
# Validate the generated specification
app.validate()
print("Specification is valid.")
# Save the specification to a JSON file
with open('openapi.json', 'w') as f:
f.write(app.dump_json(indent=2))
print("Successfully generated openapi.json")
except Exception as e:
print(f"Validation Error: {e}")
これでgenerate_spec.py
ファイルは完成です。ターミナルから実行します:Bash
python generate_spec.py
すべてが正しければ、以下の出力が表示されます:
Specification is valid.
Successfully generated openapi.json
これで、プロジェクトディレクトリに新しいファイルopenapi.json
が作成されます。これを開いて内容を確認してください。Flask APIを詳細に記述した、完璧に構造化されたOpenAPI 3.0ドキュメントが表示されます。
パート5:ドキュメントの提供
openapi.json
ファイルはマシンやクライアントSDKの生成には優れていますが、人間の開発者にとってはインタラクティブなUIの方がはるかに便利です。この最後のパートでは、生成した仕様をFlaskアプリに統合し、人気のあるSwagger UIを使用して提供します。
仕様をFlaskに統合する
まず、Flaskアプリにopenapi.json
ファイルを提供するエンドポイントを作成する必要があります。これにより、ドキュメントツールは実行中のAPIから直接仕様を取得できます。
app.py
を修正して新しいルートを追加します:Python
# app.py
# ... (keep all the existing Flask code) ...
import os
# ... (all the routes like /users, /users/{user_id}, etc.) ...
# --- Serving the OpenAPI Specification and UI ---
@app.route('/api/docs/openapi.json')
def serve_openapi_spec():
""" Serves the generated openapi.json file. """
# This assumes openapi.json is in the same directory as app.py
# In a larger app, you might want a more robust way to find the file
return app.send_static_file('openapi.json')
これが機能するためには、Flaskは静的ファイルを見つける場所を知っている必要があります。デフォルトでは、static
ディレクトリを探します。ディレクトリを作成し、そこにopenapi.json
ファイルを移動しましょう:Bash
mkdir static
mv openapi.json static/
さて、python app.py
を実行し、http://127.0.0.1:5000/api/docs/openapi.json
にアクセスします。仕様の生のJSONが表示されるはずです。
Swagger UIでインタラクティブなUIを提供する 🎨
Swagger UIは、OpenAPI準拠のAPIから美しいドキュメントを動的に生成する、依存関係のないHTML2、JavaScript、CSSアセットのコレクションです。Flaskアプリケーションから簡単に提供できます。
Templatesディレクトリを作成: FlaskはHTMLテンプレートを探すためにtemplates
という名前のディレクトリを使用します:Bash
mkdir templates
Swagger UIテンプレートを作成: templates
ディレクトリ内に、swagger_ui.html
という名前の新しいファイルを作成します。以下のHTMLコードを貼り付けます。このコードは、パブリックCDNからSwagger UIアセットをロードし、私たちの仕様ファイルをロードするように構成します:HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User API - Swagger UI</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/swagger-ui.min.css" >
<style>
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin:0;
background: #fafafa;
}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/swagger-ui-bundle.js"> </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/5.17.14/swagger-ui-standalone-preset.js"> </script>
<script>
window.onload = function() {
// Begin Swagger3 UI call region
const ui = SwaggerUIBundle({
url: "/api/docs/openapi.json", // The URL for our spec
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset4
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
// End Swagger UI call region
window.ui = ui
}
</script>
</body>
</html>
```
Flaskルートを追加: 最後に、このHTMLテンプレートをレンダリングするためのルートをapp.py
に追加します。Flaskからrender_template
をインポートする必要があります:Python
# At the top of app.py
from flask import Flask, jsonify, request, abort, render_template
# ... (all other routes) ...
@app.route('/api/docs/')
def serve_swagger_ui():
""" Serves the interactive Swagger UI documentation. """
return render_template('swagger_ui.html')
すべてをまとめる
最終的なプロジェクト構造は以下のようになります:
pyswagger-tutorial/
├── app.py
├── generate_spec.py
├── requirements.txt
├── static/
│ └── openapi.json
├── templates/
│ └── swagger_ui.html
└── venv/
さて、最終結果です。Flaskアプリが実行されていることを確認してください(python app.py
)。Webブラウザを開き、以下にアクセスします:
http://127.0.0.1:5000/api/docs/
APIの美しくインタラクティブなドキュメントページが表示されるはずです。各エンドポイントを展開したり、定義したスキーマを確認したり、「Try it out」ボタンを使用してブラウザから直接実行中のFlaskアプリケーションにライブリクエストを送信したりすることもできます。
まとめ
このチュートリアルでは、空のディレクトリから完全にドキュメント化されたAPIへと旅をしてきました。pyswagger
のオブジェクトモデルをAPIの構造にマッピングすることで、詳細なOpenAPI 3.0仕様をプログラムで構築することに成功しました。メタデータ、サーバー、再利用可能なスキーマ、パス、およびそれらのパラメーターと応答を持つ操作を定義する方法を見ました。
仕様生成(generate_spec.py
)をアプリケーションロジック(app.py
)から分離することで、APIを実装し、次にジェネレーターを実行してドキュメントを生成するというクリーンなワークフローを作成しました。このプロセスは、デコレーターベースのアプローチよりも手動ですが、比類のない制御と柔軟性を提供し、複雑なプロジェクト、レガシーコードベース、またはドキュメント標準が厳格な場合に理想的です。
最後に、生成された仕様とSwagger UIインスタンスを提供することで、APIの消費者向けに洗練されたプロフェッショナルで非常に使いやすいドキュメントポータルを提供しました。これで、ワールドクラスのAPIドキュメントを作成するための、Python開発ツールキットの強力な新しいツールが手に入りました。
開発チームが最大限の生産性で協力するための統合されたオールインワンプラットフォームが必要ですか?
Apidogはあなたのすべての要求に応え、Postmanをはるかに手頃な価格で置き換えます!