プライベートな連絡先の最初の情報
送料メール:
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
目次
1. Flask と Flask-Apispec をインストールする
1. Django と Django-Rest-Framework をインストールする
2. Django プロジェクトとアプリケーションを作成する
http://localhost:5000/swagger/ にアクセスして、生成された API ドキュメントを表示します。
APIspec の概要
Apispec は、OpenAPI (Swagger) 仕様を生成するための Python ライブラリです。これは、開発者が API ドキュメントを自動的に生成および管理し、直感的で詳細なインターフェイスの説明を提供するのに役立ちます。 Apispec を使用すると、Python 関数またはクラスのドキュメント文字列を OpenAPI 仕様に準拠したドキュメントに簡単に変換でき、ドキュメントを手動で作成する手間が軽減されます。
シンプルで使いやすい: Apispec はシンプルで使いやすい API を提供するため、すぐに使い始めることができます。
柔軟かつ強力: 複数のフレームワーク (Flask、Django など) と拡張機能をサポートし、必要に応じてドキュメント生成をカスタマイズできます。
オートメーション: ドキュメントを自動的に生成および更新することで、手動操作とメンテナンスのコストを削減します。
Apispec の使用を開始する前に、まず Apispec をインストールする必要があります。 pip を使用してインストールできます。
pip install apispec
Github プロジェクトのアドレス:
https://github.com/marshmallow-code/apispec
いくつかの簡単な例を通して、Apispec の基本的な使用法を見てみましょう。
- from apispec import APISpec
-
- spec = APISpec(
- title="My API",
- version="1.0.0",
- openapi_version="3.0.0",
- info=dict(description="This is a sample API"),
- )
- def get_user(user_id):
- """
- ---
- get:
- description: Get a user by ID
- parameters:
- - name: user_id
- in: path
- required: true
- schema:
- type: integer
- responses:
- 200:
- description: A user object
- content:
- application/json:
- schema:
- type: object
- properties:
- id:
- type: integer
- name:
- type: string
- """
- return {"id": user_id, "name": "John Doe"}
- spec.path(
- path="/users/{user_id}",
- operations=dict(
- get=dict(
- description="Get a user by ID",
- parameters=[
- {
- "name": "user_id",
- "in": "path",
- "required": True,
- "schema": {"type": "integer"},
- }
- ],
- responses={
- "200": {
- "description": "A user object",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "id": {"type": "integer"},
- "name": {"type": "string"},
- },
- }
- }
- },
- }
- },
- )
- ),
- )
pip install Flask Flask-Apispec
- from flask import Flask, jsonify
- from flask_apispec import FlaskApiSpec, doc, marshal_with
- from flask_apispec.views import MethodResource
- from marshmallow import Schema, fields
-
- app = Flask(__name__)
-
- class UserSchema(Schema):
- id = fields.Int()
- name = fields.Str()
-
- class UserResource(MethodResource):
- @doc(description='Get a user by ID', tags=['User'])
- @marshal_with(UserSchema)
- def get(self, user_id):
- return {"id": user_id, "name": "John Doe"}
-
- app.add_url_rule('/users/<int:user_id>', view_func=UserResource.as_view('user_resource'))
- docs = FlaskApiSpec(app)
- docs.register(UserResource)
-
- @app.route('/swagger/')
- def swagger_ui():
- return jsonify(docs.spec.to_dict())
-
- if __name__ == '__main__':
- app.run()
pip install django djangorestframework
- django-admin startproject myproject
- cd myproject
- django-admin startapp myapp
settings.py にrest_framework と apispec を追加します。
- INSTALLED_APPS = [
- ...
- 'rest_framework',
- 'myapp',
- 'apispec',
- ]
myapp/views.py 内:
- from rest_framework.views import APIView
- from rest_framework.response import Response
- from rest_framework.schemas import AutoSchema
-
- class UserView(APIView):
- schema = AutoSchema(
- manual_fields=[
- coreapi.Field('user_id', required=True, location='path', schema={'type': 'integer'})
- ]
- )
-
- def get(self, request, user_id):
- """
- Get a user by ID.
- ---
- responses:
- 200:
- description: A user object
- content:
- application/json:
- schema:
- type: object
- properties:
- id:
- type: integer
- name:
- type: string
- """
- return Response({"id": user_id, "name": "John Doe"})
myapp/urls.py 内:
- from django.urls import path
- from .views import UserView
-
- urlpatterns = [
- path('users/<int:user_id>/', UserView.as_view(), name='user-view'),
- ]
manage.py 内:
- from apispec import APISpec
- from rest_framework.schemas import get_schema_view
-
- spec = APISpec(
- title="My API",
- version="1.0.0",
- openapi_version="3.0.0",
- )
-
- schema_view = get_schema_view(title="My API")
- schema = schema_view.get_schema(request=None, public=True)
- spec.components.schema('User', schema)
- spec.path(path='/users/{user_id}/', operations=schema['paths']['/users/{user_id}/'])
-
- print(spec.to_yaml())
APIspec は、ジェネレーターをカスタマイズできる柔軟な拡張メカニズムを提供します。 Apispec が提供する基本クラスを継承および拡張することで、独自の生成ロジックを実装できます。
- from apispec import BasePlugin
-
- class MyPlugin(BasePlugin):
- def path_helper(self, operations, *, resource, **kwargs):
- operations.update({
- 'get': {
- 'description': 'Get a user by ID',
- 'parameters': [
- {'name': 'user_id', 'in': 'path', 'required': True, 'schema': {'type': 'integer'}}
- ],
- 'responses': {
- '200': {
- 'description': 'A user object',
- 'content': {
- 'application/json': {
- 'schema': {
- 'type': 'object',
- 'properties': {
- 'id': {'type': 'integer'},
- 'name': {'type': 'string'}
- }
- }
- }
- }
- }
- }
- }
- })
-
- spec = APISpec(
- title="My API",
- version="1.0.0",
- openapi_version="3.0.0",
- plugins=[MyPlugin()],
- )
Apispec は、Flask、Django、Falcon など、さまざまな一般的な Python フレームワークをサポートしています。ニーズに応じて適切なフレームワークとプラグインを選択し、API ドキュメントを迅速に生成できます。
Apispec は、関数またはクラスのドキュメント文字列に基づいてインターフェイス ドキュメントを自動的に生成できるため、ドキュメントを手動で作成する作業負荷が軽減されます。
- def get_user(user_id):
- """
- ---
- get:
- description: Get a user by ID
- parameters:
- - name: user_id
- in: path
- required: true
- schema:
- type: integer
- responses:
- 200:
- description: A user object
- content:
- application/json:
- schema:
- type: object
- properties:
- id:
- type: integer
- name:
- type: string
- """
- return {"id": user_id, "name": "John Doe"}
Apispec は、Swagger UI、ReDoc などの多くのサードパーティ ツールと統合して、直感的なインターフェイスのドキュメント表示およびテスト機能を提供できます。
- from flask import Flask, jsonify
- from flask_apispec import FlaskApiSpec
-
- app = Flask(__name__)
-
- @app.route('/users/<int:user_id>', methods=['GET'])
- def get_user(user_id):
- """
- ---
- get:
- description: Get a user by ID
- parameters:
- - name: user_id
- in: path
- required: true
- schema:
- type: integer
- responses:
- 200:
- description: A user object
- content:
- application/json:
- schema:
- type: object
- properties:
- id:
- type: integer
- name:
- type: string
- """
- return jsonify({"id": user_id, "name": "John Doe"})
-
- docs = FlaskApiSpec(app)
- docs.register(get_user)
-
- if __name__ == '__main__':
- app.run()
完全な API ドキュメント システムを構築する
単純なユーザー管理システムがあり、その API を文書化する必要があるとします。当社の API には、ユーザーの追加、削除、変更、クエリ操作に加えて、いくつかの基本的な ID 認証機能が含まれています。
- user_management/
- ├── app.py
- ├── models.py
- ├── views.py
- ├── serializers.py
- └── requirements.txt
依存関係をrequirements.txtに追加します。
- Flask
- Flask-RESTful
- Flask-SQLAlchemy
- Flask-Migrate
- apispec
- flask-apispec
次のコマンドを実行して依存関係をインストールします。
pip install -r requirements.txt
models.py でユーザー モデルを定義します。
- from flask_sqlalchemy import SQLAlchemy
-
- db = SQLAlchemy()
-
- class User(db.Model):
- id = db.Column(db.Integer, primary_key=True)
- name = db.Column(db.String(80), nullable=False)
- email = db.Column(db.String(120), unique=True, nullable=False)
serializers.py でユーザー シリアライザーを定義します。
- from marshmallow import Schema, fields
-
- class UserSchema(Schema):
- id = fields.Int(dump_only=True)
- name = fields.Str(required=True)
- email = fields.Email(required=True)
-
views.py でビューを定義します。
- from flask import request
- from flask_restful import Resource
- from models import User, db
- from serializers import UserSchema
-
- class UserResource(Resource):
- def get(self, user_id):
- user = User.query.get_or_404(user_id)
- schema = UserSchema()
- return schema.dump(user)
-
- def post(self):
- schema = UserSchema()
- user = schema.load(request.json)
- db.session.add(user)
- db.session.commit()
- return schema.dump(user), 201
-
- def put(self, user_id):
- user = User.query.get_or_404(user_id)
- schema = UserSchema(partial=True)
- updated_user = schema.load(request.json, instance=user)
- db.session.commit()
- return schema.dump(updated_user)
-
- def delete(self, user_id):
- user = User.query.get_or_404(user_id)
- db.session.delete(user)
- db.session.commit()
- return '', 204
app.py 内:
- from flask import Flask
- from flask_restful import Api
- from flask_migrate import Migrate
- from models import db
- from views import UserResource
- from flask_apispec import FlaskApiSpec
- from flask_apispec.extension import FlaskApiSpec
-
- app = Flask(__name__)
- app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
- db.init_app(app)
- migrate = Migrate(app, db)
- api = Api(app)
-
- api.add_resource(UserResource, '/users/<int:user_id>')
-
- docs = FlaskApiSpec(app)
- docs.register(UserResource)
-
- if __name__ == '__main__':
- app.run()
次のコマンドを実行してアプリケーションを起動します。
python app.py
1. ドキュメントとコードの同期を保つ
ドキュメントと実際の API の間の不一致を避けるために、ドキュメントが常にコードと同期していることを確認してください。 CI/CD ツールを使用して、ドキュメントを自動的に生成および展開できます。
2. アノテーションとデコレータを使用する
コメントとデコレータを使用すると、ドキュメントをより簡潔で読みやすくすることができます。たとえば、Flask-Apispec の @doc デコレーターを使用して、ドキュメント情報をビュー関数に追加します。
3. グローバルパラメータと応答を定義する
よく使用されるパラメータと応答については、Apispec でグローバル パラメータと応答テンプレートを定義して、コードの繰り返しを減らすことができます。
- spec.components.parameter("user_id", "path", schema={"type": "integer"}, required=True)
- spec.components.response("User", {
- "description": "A user object",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "id": {"type": "integer"},
- "name": {"type": "string"}
- }
- }
- }
- }
- })
4. ドキュメントを定期的に確認して更新する
正確さと完全性を確保するために、ドキュメントを定期的に確認して更新します。これは、文書レビューサイクルを設定するか、文書レビュープロセスを導入することで実現できます。
その他の機能と詳細な使用方法については、公式ドキュメントを参照してください。
https://apispec.readthedocs.io/en/latest
この記事を通じて、Apispec の基本を理解し、習得できたと思います。基本的な使い方から高度な機能、実践事例やベストプラクティスまで、Apispec を使用して API ドキュメントを生成および保守する方法を包括的に紹介します。
この知識を実際のプロジェクトに適用して、API に明るさを加えていただければ幸いです。