使用示例
注意: flasgger 中引用一个外部文件,在内网中不可访问,导致页面一直在刷新,
这行# 简易示例
import random
from flask import Flask, jsonify, request
from flasgger import Swagger
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)
使用配置文件方式
#! /usr/bin/python3
# -*- coding:utf-8 -*-
import random
from flask import Flask, jsonify, request
from flasgger import Swagger, swag_from
app = Flask(__name__)
Swagger(app)
@app.route('/api//', methods=['GET'])
@swag_from("api_get.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)
api_get
中,再使用装饰器 swag_from 即可达成一样的效果https://github.com/Laurel-rao/csdn_demo/tree/master/flasgger_use
swagger,包括两大部分,一部分是全局配置,一部分是具体url的配置
https://swagger.io/docs/specification/basic-structure/
https://github.com/OAI/OpenAPI-Specification/tree/OpenAPI.next
python 配置全局配置
swagger_config = {
"headers": [
],
"specs": [
{
"endpoint": 'apispec_2',
"route": '/apispecification.json',
"rule_filter": lambda rule: True, # all in
"model_filter": lambda tag: True, # all in
}
],
"static_url_path": "/flasgger_static",
# "static_folder": "static", # must be set by user
"swagger_ui": True,
"specs_route": "/doc/"
}
template_config = {
"info": {
"title": "Sample API",
"description": "Hahaha, this is a API kingdom!",
"version": "1.0.0"
}
}
Swagger(app, template=template_config, config=swagger_config)
in : body
,可以将参数放入请求体,适用于POST
请求未完待续,目前发现swagger 还有很多不方便的地方,暂时停更