当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

flask-restful-swagger

A Swagger spec extractor for flask-restful
授权协议 MIT License
开发语言 Python
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 张森
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

flask-restful-swagger

flask_restful_swagger-automation
flask_restful_swagger-automation

What is flask-restful-swagger?

flask-restful-swagger is a wrapper for flask-restful which enables swagger support.

In essence, you just need to wrap the Api instance and add a few python decorators to get full swagger support.

Installation:

Install:

pip install flask-restful-swagger

(This installs flask-restful as well)

See Some Quick Examples:

PYTHONPATH=. python examples/basic.py
PYTHONPATH=. python examples/blueprints.py
PYTHONPATH=. python examples/inheritance.py

Browse to: http://localhost:5000/api/spec.html

Contributing, and Making Improvements:

How To:

In your program, where you'd usually just use flask-restful, add just a little bit of sauce and get a swagger spec out.

from flask import Flask
from flask_restful import Api
from flask_restful_swagger import swagger

app = Flask(__name__)

###################################
# Wrap the Api with swagger.docs. It is a thin wrapper around the Api class that adds some swagger smarts
api = swagger.docs(Api(app), apiVersion='0.1')
###################################


# You may decorate your operation with @swagger.operation
class Todo(Resource):
    "Describing elephants"
    @swagger.operation(
        notes='some really good notes',
        responseClass=ModelClass.__name__,
        nickname='upload',
        parameters=[
            {
              "name": "body",
              "description": "blueprint object that needs to be added. YAML.",
              "required": True,
              "allowMultiple": False,
              "dataType": ModelClass2.__name__,
              "paramType": "body"
            }
          ],
        responseMessages=[
            {
              "code": 201,
              "message": "Created. The URL of the created blueprint should be in the Location header"
            },
            {
              "code": 405,
              "message": "Invalid input"
            }
          ]
        )
    def get(self, todo_id):
    
# Operations not decorated with @swagger.operation do not get added to the swagger docs

class Todo(Resource):
    def options(self, todo_id):
        """
        I'm not visible in the swagger docs
        """
        pass


# Then you add_resource as you usually would

api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<string:todo_id>')

# You define models like this:
@swagger.model
class TodoItem:
  "A description ..."
  pass

# Swagger json:
    "models": {
        "TodoItemWithArgs": {
            "description": "A description...",
            "id": "TodoItem",
        },

# If you declare an __init__ method with meaningful arguments then those args could be used to deduce the swagger model fields.
@swagger.model
class TodoItemWithArgs:
  "A description ..."
  def __init__(self, arg1, arg2, arg3='123'):
    pass

# Swagger json:
    "models": {
        "TodoItemWithArgs": {
            "description": "A description...",
            "id": "TodoItem",
            "properties": {
                "arg1": {
                    "type": "string"
                },
                "arg2": {
                    "type": "string"
                },
                "arg3": {
                    "default": "123",
                    "type": "string"
                }
            },
            "required": [
                "arg1",
                "arg2"
            ]
        },


# Additionally, if the model class has a `resource_fields` class member then flask-restful-swagger is able to deduce the swagger spec by this list of fields.

@swagger.model
class TodoItemWithResourceFields:
  resource_fields = {
      'a_string': fields.String
  }

# Swagger json:
    "models": {
        "TodoItemWithResourceFields": {
            "id": "TodoItemWithResourceFields",
            "properties": {
                "a_string": {
                    "type": "string"
                },
            }
        }

# And in order to close the loop with flask-restify you'd also need to tell flask-restify to @marshal_with the same list of fields when defining your methods.
# Example:

@marshal_with(TodoItemWithResourceFields.resource_fields)
def get()
  return ...

Using @marshal_with

Let us recap usage of @marshal_with.flask-restful has a decorator @marshal_with. With the following setup it's possible to define the swagger model types with the same logic as @marshal_with.

You have to:

# Define your model with resource_fields
@swagger.model
class TodoItemWithResourceFields:
  resource_fields = {
      'a_string': fields.String,
      'a_second_string': fields.String(attribute='a_second_string_field_name')
  }

# And use @marshal_with(YourClass.resource_fields):
@marshal_with(TodoItemWithResourceFields.resource_fields)
def get()
  return ...

Running and testing

Now run your flask app

python example.py

And visit:

curl http://localhost:5000/api/spec.json

Passing more metadata to swagger

When creating the swagger.docs object you may pass additional arguments, such as the following:

api_spec_url - where to serve the swagger spec from. Default is /api/spec. This will make the json
available at /api/spec as well as /api/spec.json and will also present a nice interactive
HTML interface at /api/spec.html

apiVersion - passed directly to swagger as the apiVersion attribute. Default: 0.0

basePath - passed directly to swagger as the basePath attribute. Default: 'http://localhost:5000' (do not include a slash at the end)

resourcePath - same as before. default: '/'

produces - same as before, passed directly to swagger. The default is ["application/json"]

swaggerVersion - passed directly to swagger. Default: 1.2

description - description of this API endpoint. Defaults to 'Auto generated API docs by flask-restful-swagger'

Accessing the result json spec and an Interactive HTML interface

Assuming you provided swagger.docs with a parameter api_spec_url='/api/spec' (or left out in which case the default is '/api/spec') you may access the resulting json at /api/spec.json.You may also access /api/spec.html where you'd find an interactive HTML page that lets you play with the API to some extent.

Here's how this HTML page would look like:

Accessing individual endpoints (.help.json)

flask-restful-swagger adds some useful help pages (well, json documents) to each of your resources. This isn't part of the swagger spec, but could be useful anyhow.With each endpoint you register, there's also an automatically registered help endpoint which ends with a .help.json extension.So for example when registering the resource api.add_resource(TodoList, '/todos') you may access the actual api through the url /todos and you may also access the help page at /todos.help.json. This help page spits out the relevant json content only for this endpoint (as opposed to /api/spec.json which spits out the entire swagger document, which could be daunting)

Example:

### python:

> api.add_resource(TodoList, '/todos')

### Shell:

$ curl localhost:5000/todos.help.json
{
    "description": null,
    "operations": [
        {
            "method": "GET",
            "nickname": "nickname",
            "parameters": [],
            "summary": null
        },
        {
            "method": "POST",
            "nickname": "create",
            "notes": "Creates a new TODO item",
            "parameters": [
                {
                    "allowMultiple": false,
                    "dataType": "TodoItem",
                    "description": "A TODO item",
                    "name": "body",
                    "paramType": "body",
                    "required": true
                }
            ],
            "responseClass": "TodoItem",
            "responseMessages": [
                {
                    "code": 201,
                    "message": "Created. The URL of the created blueprint should be in the Location header"
                },
                {
                    "code": 405,
                    "message": "Invalid input"
                }
            ],
            "summary": null
        }
    ],
    "path": "/todos"
}

When registering an endpoint with path parameters (e.g. /todos/<string:id>) then the .help url is may be found at the swagger path, e.g. /todos/{id}.help.json where {id} is just that - a literal string "{id}"

Example:

### Python:
> api.add_resource(Todo, '/todos/<string:todo_id>')

### Shell:
 # You might need to quote and escape to prevent the shell from messing around

curl 'localhost:5000/todos/\{todo_id\}.help.json'
{
    "description": "My TODO API",
    "operations": [
        {
            "method": "DELETE",
            "nickname": "nickname",
            "parameters": [
                {
                    "dataType": "string",
                    "name": "todo_id"
                }
            ],
            "summary": null
        },
        {
            "method": "GET",
            "nickname": "get",
            "notes": "get a todo item by ID",
            "parameters": [
                {
                    "allowMultiple": false,
                    "dataType": "string",
                    "description": "The ID of the TODO item",
                    "name": "todo_id_x",
                    "paramType": "path",
                    "required": true
                }
            ],
            "responseClass": "TodoItemWithResourceFields",
            "summary": "Get a todo task"
        },
        {
            "method": "PUT",
            "nickname": "nickname",
            "parameters": [
                {
                    "dataType": "string",
                    "name": "todo_id"
                }
            ],
            "summary": null
        }
    ],
    "path": "/todos/{todo_id}"
}

Accessing individual endpoints as HTML (.help.html)

Similarly to the .help.json URLs we have .help.html pages which are static HTML pages to document your APIs.Here's a screenshot to illustrate:

This project is part of the Cloudify Cosmo project

  • 由于写完flask接口后,需要向前端提供swagger接口文档,因此需要自动生成swagger文档。 1. 安装flask-restplus 采用如下命令安装flask-restplus pip install flask-restplus==0.13.0 安装完成后导入包时报错,这是因为新版的werkzeug中该模块导入发生了变化,需要手动修改下 cannot import name 'cac

  • 本文介绍的内容最好结合本人关于Blueprint讲解的文章去理解 Flask-RESTful 提供的最主要的基础就是资源(resources)。资源(Resources)是构建在 Flask 可拔插视图 之上,只要在你的资源(resource)上定义方法就能够容易地访问多个 HTTP 方法,这是官方关于flask_restful的介绍,不多讲解理论,直接上代码。 from flask_restfu

  • 1、使用教程 data_api.py from flask import Flask from flask_restplus import Api from flask import request from flask_restplus import Resource, fields import json from weibo_params import news_input, news_ou

  • 我有两个dataframe: A : 从本地csv读取 B:用request 向api 请求 我需要在得到这两个dataframe后合并成一个,然后再做成api提供出去。 我看了很多教程,认为flaskrestful api 可能比较合适,但尝试了不成功,数据不会刷新。 请问有没有什么好的办法处理上述需求? api是不停更新的,不是一次性,所以合并出来的新dataframe的数据也是要同步更新的,

  • flask-resplus关闭swagger方法 工厂方法中添加 add_specs=False api.init_app(app, add_specs=False)

 相关资料
  • 在前面,我们介绍了 REST Web 服务,并使用 Flask 提供服务。这里,我们使用第三方库 Flask-RESTful,它使得在 Flask 中提供 REST 服务变得更加简单。 安装 使用 pip 安装: $ pip install flask-restful 使用 下面我们主要使用官方文档的例子进行说明。 Hello World 我们先来看一个简单的例子。 # -*- coding: u

  • flask-restful-example flask后端开发接口示例,利用Flask开发后端API接口。包含基本的项目配置、统一响应、MySQL和Redis数据库操作、定时任务、图片生成、项目部署、用户权限认证、报表输出、无限层级生成目录树、阿里云手机验证码验证、微信授权、Celery、单元测试、Drone等模块。 一、系列文章 Flask后端实践 连载一 加载yaml配置文件 Flask后端实

  • cookiecutter-flask-restful Cookiecutter template for flask restful, including blueprints, application factory, and more Introduction This cookie cutter is a very simple boilerplate for starting a REST

  • 问题内容: 我想知道如何通过创建API服务来上传文件? 路线 然后是HTML 我已经在服务器端启用了CORS 如果重要的话,我正在使用angular.js作为前端和ng-upload,但是也可以使用CURL语句! 问题答案: 您应该处理流,如果它是wav,则上面的代码有效。对于图像,您应该存储在数据库上或上传到AWS S3或Google Storage

  • Flask-RESTful 是一个 Flask 扩展,它添加了快速构建 REST APIs 的支持。它当然也是一个能够跟你现有的ORM/库协同工作的轻量级的扩展。Flask-RESTful 鼓励以最小设置的最佳实践。如果你熟悉 Flask 的话,Flask-RESTful 应该很容易上手。 使用 pip 安装 Flask-RESTful: pip install flask-restful 开发

  • 翻译者注:本系列的原文名为:Designing a RESTful API with Python and Flask ,作者是 Miguel Grinberg 。 近些年来 REST (REpresentational State Transfer) 已经变成了 web services 和 web APIs 的标配。 在本文中我将向你展示如何简单地使用 Python 和 Flask 框架来创建