PythonとPySwaggerでOpenAPIドキュメントを生成するステップバイステップチュートリアル

Rebecca Kovács

Rebecca Kovács

12 6月 2025

PythonとPySwaggerでOpenAPIドキュメントを生成するステップバイステップチュートリアル

包括的で正確な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も手に入ります。

💡
美しいAPIドキュメントを生成する優れたAPIテストツールが必要ですか?

開発チームが最大限の生産性で協力するための統合されたオールインワンプラットフォームが必要ですか?

Apidogはあなたのすべての要求に応え、Postmanをはるかに手頃な価格で置き換えます
button

パート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から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

infoserversセクションは簡単に埋めることができます: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メソッド)を定義します。各操作は、summarydescriptionparametersrequestBody、および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オブジェクトはデータモデルを定義します。その型(objectstringinteger)とプロパティを指定できます: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ステータスコードに対する応答の構造を定義します。これには、descriptioncontentが含まれ、メディアタイプ(例: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つの基本的なエンドポイントを実装します:

  1. GET /users: すべてのユーザーのリストを取得します。
  2. POST /users: 新しいユーザーを作成します。
  3. GET /users/{user_id}: IDで単一のユーザーを取得します。
  4. 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または同様のツールでテストできます:

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つの操作:GETPOSTを定義します。

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_refA(「アクセス」を意味します)の使用に注目してください。

4. /users/{user_id}エンドポイントのドキュメント化

次に、単一のユーザーと対話するためのパスをドキュメント化します。このパスには、パスパラメーター{user_id}が含まれます。

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開発ツールキットの強力な新しいツールが手に入りました。

💡
美しいAPIドキュメントを生成する優れたAPIテストツールが必要ですか?

開発チームが最大限の生産性で協力するための統合されたオールインワンプラットフォームが必要ですか?

Apidogはあなたのすべての要求に応え、Postmanをはるかに手頃な価格で置き換えます
button

ApidogでAPIデザイン中心のアプローチを取る

APIの開発と利用をよりシンプルなことにする方法を発見できる