目录
1、安装 Django 和 Django-Rest-Framework
访问 http://localhost:5000/swagger/ 查看生成的 API 文档。
01什么是 Apispec?
Apispec 简介
Apispec 是一个用于生成 OpenAPI(Swagger)规范的 Python 库。它能够帮助开发者自动生成和维护 API 文档,提供直观、详细的接口说明。通过 Apispec,我们可以轻松地将 Python 函数或类的文档字符串转换为符合 OpenAPI 规范的文档,减少手动编写文档的麻烦。
为什么选择 Apispec?
-
简洁易用:Apispec 提供了简单易用的 API,让你可以快速上手。
-
灵活强大:支持多种框架(如 Flask、Django)和扩展,让你可以根据需要定制化文档生成。
-
自动化:通过自动生成和更新文档,减少手动操作和维护成本。
安装与配置
在开始使用 Apispec 之前,我们需要先进行安装。你可以使用 pip 进行安装:
pip install apispec
Github 项目地址:
https://github.com/marshmallow-code/apispec
02Apispec 的基本用法
让我们通过几个简单的例子来看看 Apispec 的基本用法。
生成简单的 API 文档
1、创建 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"),
)
2、定义 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"}
3、添加路径到 Apispec
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"},
},
}
}
},
}
},
)
),
)
集成 Flask 和 Apispec
1、安装 Flask 和 Flask-Apispec
pip install Flask Flask-Apispec
2、创建 Flask 应用
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()