转载:https://changsiyuan.github.io/2017/05/20/2017-5-20-flasgger/
本文介绍了flasgger的用法和不足之处。
首先,需要在项目中安装flasgger,具体方法有两种:
安装后,使用下面的程序框架,搭建最简单的web api:
app = Flask(__name__)
Swagger(app)
@app.route('/api//', methods=['GET'])
def index(language):
"""
This is the language awesomeness API
Call this api passing a language name and get back its features
---
tags:
- Awesomeness Language API
parameters:
- name: language
in: path
type: string
required: true
description: The language name
- name: size
in: query
type: integer
description: size of awesomeness
responses:
500:
description: Error The language is not awesome!
200:
description: A language with its awesomeness
schema:
id: awesome
properties:
language:
type: string
description: The language name
default: Lua
features:
type: array
description: The awesomeness list
items:
type: string
default: ["perfect", "simple", "lovely"]
"""
language = language.lower().strip()
features = [
"awesome", "great", "dynamic",
"simple", "powerful", "amazing",
"perfect", "beauty", "lovely"
]
size = int(request.args.get('size', 1))
if language in ['php', 'vb', 'visualbasic', 'actionscript']:
return "An error occurred, invalid language for awesomeness", 500
return jsonify(
language=language,
features=random.sample(features, size)
)
app.run(debug=True)
从上面的程序我们可以看出,只要将yaml格式的flasgger描述性程序放置在两组双引号之间的位置,即可实现flasgger的基本功能;
访问http://localhost:5000/apidocs/index.html 即可看到flasgger页面
当然,上面的yaml描述性程序可以放置在单独的文件中,那么api中用@符号引入这个文件即可:
import random
from flask import Flask, jsonify, request
from flasgger import Swagger
from flasgger.utils import swag_from
app = Flask(__name__)
Swagger(app)
@app.route('/api//', methods=['GET'])
@swag_from('index.yml')
def index(language):
language = language.lower().strip()
features = [
"awesome", "great", "dynamic",
"simple", "powerful", "amazing",
"perfect", "beauty", "lovely"
]
size = int(request.args.get('size', 1))
if language in ['php', 'vb', 'visualbasic', 'actionscript']:
return "An error occurred, invalid language for awesomeness", 500
return jsonify(
language=language,
features=random.sample(features, size)
)
app.run(debug=True)
flasgger介绍
flasgger文档
flasgger源码
swagger官网