내 연락처 정보
우편메소피아@프로톤메일.com
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
목차
1. Django 및 Django-Rest-Framework 설치
생성된 API 문서를 보려면 http://localhost:5000/swagger/를 방문하세요.
API사양 소개
Apispec은 OpenAPI(Swagger) 사양을 생성하기 위한 Python 라이브러리입니다. 개발자가 API 문서를 자동으로 생성 및 유지 관리하고 직관적이고 자세한 인터페이스 설명을 제공하는 데 도움이 될 수 있습니다. Apispec을 통해 Python 함수 또는 클래스의 문서 문자열을 OpenAPI 사양을 준수하는 문서로 쉽게 변환하여 수동으로 문서를 작성하는 수고를 줄일 수 있습니다.
간단하고 사용하기 쉬운: Apispec은 간단하고 사용하기 쉬운 API를 제공하므로 빠르게 시작할 수 있습니다.
유연하고 강력함: 여러 프레임워크(예: Flask, Django) 및 확장을 지원하므로 필요에 따라 문서 생성을 사용자 정의할 수 있습니다.
오토메이션: 문서를 자동으로 생성하고 업데이트하여 수동 운영 및 유지 관리 비용을 절감합니다.
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에는 사용자 추가, 삭제, 수정 및 쿼리 작업과 일부 기본 신원 인증 기능이 포함되어 있습니다.
- user_management/
- ├── app.py
- ├── models.py
- ├── views.py
- ├── serializers.py
- └── requirements.txt
요구사항.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에 밝기를 추가할 수 있기를 바랍니다.