Giter VIP home page Giter VIP logo

flask-restful-swagger's Introduction

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:

An example /api/spec.html page

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: An example .help.html page

This project is part of the Cloudify Cosmo project

flask-restful-swagger's People

Contributors

adelavega avatar aectann avatar ashrafpatel avatar dankilman avatar dekimsey avatar eli-b avatar flexme avatar kumy avatar lavie avatar msoltysik avatar niall-byrne avatar nukemberg avatar rantav avatar richtera avatar seonaid avatar simstre avatar slafi-vw avatar sobolevn avatar tjakobsen avatar turbo87 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-restful-swagger's Issues

Incoherent urls in main html when using more than 1 blueprint, with different blueprint url_prefix

Hi,
When you define more than 1 blueprint without the same api_prefix (for REST API versioning) and different api_spec_url (when testing a tunned api_spec_url and forgetting old /api/spec on in the other blueprint), the last blueprint registration override the api_spec_static global variable and in the .js urls of the main html, you get incoherent api_spec_url according to the non-last blueprints api_prefix

proposal with this comit: lounagen@11d41ef

(inside pull request #62 )

regards

OAuth2 API authorization

Hi guys,

I've seen that Swagger supports operations on a OAuth2 protected API. I've been trying to hack something in flask-restful-swagger to support it without much success.

Any ideas on how to do this?

Cheers

[bug] AttributeError: 'ShellAPI' object has no attribute '__mro__'

Using flask-restful-swagger on ShellAPI(), registered using:

    # Create and add each resource
    atom_collection_api = AtomCollectionAPI.new(self.atomspace)
    atom_types_api = TypesAPI()
    shell_api = ShellAPI()
    scheme_api = SchemeAPI.new(self.atomspace)

    self.api.add_resource(atom_collection_api,
                          '/api/v1.1/atoms',
                          '/api/v1.1/atoms/<int:id>', endpoint='atoms')
    self.api.add_resource(atom_types_api,
                          '/api/v1.1/types',
                          endpoint='types')
    self.api.add_resource(shell_api,
                          '/api/v1.1/shell',
                          endpoint='shell')
    self.api.add_resource(scheme_api,
                          '/api/v1.1/scheme',
                          endpoint='scheme')

throws:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "../opencog/python/web/api/restapi.py", line 55, in invoke
    self.api = RESTAPI(self.atomspace)
  File "/home/ceefour/git/opencog/opencog/python/web/api/apimain.py", line 55, in __init__
    endpoint='shell')
  File "/usr/local/lib/python2.7/dist-packages/flask_restful_swagger/swagger.py", line 21, in add_resource
    endpoint = swagger_endpoint(resource, path)
  File "/usr/local/lib/python2.7/dist-packages/flask_restful_swagger/swagger.py", line 135, in swagger_endpoint
    endpoint = SwaggerEndpoint(resource, path)
  File "/usr/local/lib/python2.7/dist-packages/flask_restful_swagger/swagger.py", line 152, in __init__
    self.operations = self.extract_operations(resource, path_arguments)
  File "/usr/local/lib/python2.7/dist-packages/flask_restful_swagger/swagger.py", line 160, in extract_operations
    for cls in resource.__mro__:
AttributeError: 'ShellAPI' object has no attribute '__mro__'

handle optional object ids in url

It's useful to consolidate GET requests for single or multiple objects as follows:

class Todo(Resource):
    @swagger.operation()
    def get(self, todo_id=None):
        # return single or multiple todos depending if todo_id is None
api.add_resource(Todo, '/todo', '/todo/<todo_id>')

If I understand correctly, flask-restful-swagger only recognizes the first url and ignores the second url option.
Perhaps we could support multiple decorators, one per url?

localhost deployment failed due to CORS errors

Steps to reproduce

  1. Install flask-restful-swagger
  2. Run python example.py. The API JSON is served on http://localhost:5000/api/spec.json.
  3. Download swagger-ui to /tmp
  4. Open file:///tmp//swagger-ui-master/dist/index.html
  5. Change the request URL and notice that the API can't be loaded:
    screen shot 2014-01-23 at 1 37 52 pm

Analysis

The error: Can't read from server. It may not have the appropriate access-control-origin settings. is caused by a CORS issue: Flask refuses to serve requests that were originated outside from a different domain name.

Solution

This can easily be fixed by adding a Access-Control-Allow-Origin: * header to the API response. This is supported by flask's @crossdomain(origin='*') decorator.

Looking for a maintainer for this project

flask-restful-swagger started as a way to solve my own pain point, in a project I was working on about a year ago. It had solved this pain for me as well as for others.
The project right now has 62 github stars, 25 forks and close to 3k downloads from pypi during the past month.
The project had seen a good number of pull request and bug reports and I was very happy with the community uptake.

However, in the past months I had moved to another job and although flask-restful-swagger is still very useful for the project it was initially written for, I'm no longer working on this project and I find it very hard to give flask-restful-swagger its proper attention. The community is providing excellent feedback and pull requests, but a project needs a dedicated maintainer and right now I unfortunately cannot fulfill this commitment.

I'm looking for someone from the community to step up. If found appropriate, you will get commit rights, become the official maintainer and world fame to follow. In seriousness, it does not imply more that supposedly 1-2 hours per week in general, unless you're currently working on something bigger for the project.

Roadmap includes:

  • testing and automation so that the project would be more approachable for new devs (some is in place but not enough, project unit test is missing and CI).
  • Implement more intuitive request parameters #18
  • better community support through a mailing list, IRC etc
  • Whatever's on your mind that you think is useful and the community would love. That's one of the great things in being a maintainer.

Please either comment on this issue or reach out directly to me: rantav@gmail

Thank you all!!!

Requesting /docs gives 404 in examples

It appear that commit 82f4ff9 broke /docs in the examples, because the path to static/ is no longer valid (since it's in a parent directory).

Repro:

  1. Clone 82f4ff9

  2. Run the example

    $ PYTHONPATH=. python examples/basic.py

  3. /docs successfully redirects

    $ curl --head http://localhost:5000/docs
    HTTP/1.0 302 FOUND
    Content-Type: text/html; charset=utf-8
    Content-Length: 241
    Location: http://localhost:5000/static/docs.html
    Server: Werkzeug/0.9.6 Python/2.7.5
    Date: Mon, 14 Jul 2014 15:08:32 GMT

  4. /static/docs.html not found:

    $ curl --head http://localhost:5000/static/docs.html
    HTTP/1.0 404 NOT FOUND
    Content-Type: text/html
    Content-Length: 233
    Server: Werkzeug/0.9.6 Python/2.7.5
    Date: Mon, 14 Jul 2014 15:08:36 GMT

One simple way to fix this is to add a symlink to ..\static in the examples directory. I will issue a pull request for this, but I'm happy for someone else to fix it a different way.

Issues with multiple end points with similar names

I have upgraded from 0.12 to 0.15 and am seeing some breakage. I have multiple endpoints with similar paths as such:

#fanfeed endpoints
api.add_resource(feeditems.GetFanFeed, '/api/feeditems/<string:showId>/<string:catname>/<string:modified>')
api.add_resource(feeditems.PostFeedItem, '/api/feeditems')
api.add_resource(feeditems.UpdateFeedItem, '/api/feeditems', '/api/feeditems/<string:uuid>')
api.add_resource(feeditems.DeleteFeedItem, '/api/feeditems/<string:showid>/<string:uuid>')

When processing the second add to the API I get the following exception:

ValueError: This endpoint (/api/feeditems/help) is already set to the class SwaggerResource.

Is there a simple way to resolve this? I moved to 0.15 from 0.12 due to come issued with using the "Try it out!" button with posts containing both a JSON request body and query parameters arising from swagger-ui itself.. Might 0.14 or 0.13 be a better option to avoid both issues?

Does flask-restful-swagger 0.12 support python 3?

The copy of flask-restful-swagger 0.12 on pypi doesn't specify the py version and doesn't work with python 3. However, the master branch is tagged with version 0.12 and does support python 3. Does pypi need to be updated?

Error extract operations

If any method (get, post,put, or delete) are not defined on a resource, swagger crashes, on file swagger.py, on line 98 you should validate if the method exist... and else, you should continue witch other one. Not all resources contains all methods.

My fast solution:

for method in resource.methods:
++ if method.lower() not in resource.dict:
++ continue
method_impl = resource.dict[method.lower()]

I hope this helps!

Dynamic responseClass in the swagger.operation decorator

I have a restful resource that takes an argument specifying the database table that it should query. The tables are each also set up as swagger models and the resource correctly returns results based on which one I choose to access. The problem is that I can find no way to access the function's variables from the decorator so cannot assign a responseClass.

I am very new to understanding how decorators work: is it possible to override the decorator so that the function variables can be accessed? Is there another means to access them (it knows about the required arguments somehow when it generates the documentation)?

Support for SQLAlchemy models

Applying the @swagger.model on a SQLAlchemy class, throws an Exception when using this class.

sqlalchemy.exc.InvalidRequestError
InvalidRequestError: SQL expression, column, or mapped entity expected - got '<function User at 0xaa5f304>'

As a workaround, i have to use this code, creating a "secondary" class.

@swagger.model
class User:
   resource_fields  = {c.name: re.search(', ([^\(]+)',str(c.proxy_set)).group(1) for c in classes.User.__table__.columns}

Please note that classes.User is my original SQLAlchemy class.

Is kind of dirty, but does the job.

How to add authorization protection on API?

Is there a mechanism to indicate to flask-restful-swagger that certain endpoints require authorization headers on the requests? And a way to indicate what should be in that authorization header?

How can I send POST data as JSON?

Hi,

When using the UI (api/spec.html) I want to test out my endpoints by sending in POST data in the form of application/json. The ui does show that the content type is application/json

image

But when I click "Try it out!" it doesn't actually create a JSON object with the param name as the key, it just sends the parameter as plain text. Does anyone know how to get the ui to send the parameters as formatted json objects?

Thanks!

How to customize swagger html

Hi.

In a project I want to customize the default swagger web interface.
What's the easiest way to do it? I haven't found any documentation.

I could just edit the files in the static/ folder but I wanted to know if there's some mechanism like copying the static folder from this plugin to my root folder and just edit them there.

The UI eagerly % encodes the values.

The UI currently calls encodeURIComponent, which ends up doing a percent encode on the parameters, which breaks the the values on form submission. Line 7742 in static/all.js should go from map[o.name] = encodeURI(o.value); to map[o.name] = o.value;

Intuit request parameters from reqparse?

First off, great work! ๐Ÿ˜„

An idea: Flask-restful has a module called reqparse that is intended to be used as the main way to consume request parameters from within an endpoint. I am wondering if it could be useful to introspect on an endpoint's reqparse.RequestParser instance to generate the params for the swagger docs? I think it could be really cool to have one interface for generating this as a high-level option, where the @swagger.operation decorator could still be very useful for more granular specs.

What do you think? I could see some challenges implementing this (mainly where to scope the RequestParser instance). I'd be willing to have a crack at it if you think it's a compelling case.

overwrite parameters

Parameters that are inferred from the resource URL are not over-written by those defined in swagger.operation declarations.

allowMultiple=True not being parsed per spec

According to the Swagger spec, setting allowMultiple = True will cause a CSV string (comma-separated values) to be converted to an array. The caveat is this field may be used only if paramType is "query", "header" or "path".

In contrast, flask-restful's reqparse can allow mutiple values too by setting action="append", but it's mechanism is to pass the same key several times. Per the documentation, this is how such multiple values would be passed with curl:
curl http://api.example.com -d "Name=bob" -d "Name=sue" -d "Name=joe" . Digging into curl's documentation, the -d flag sends form data. This would match Swagger's paramType="form", which is incompatible with the allowMutliple=True setting.

It seems the Swagger spec and reqparse are incompatible in this way. However, as Swagger is only a documentation spec, and not an implementation spec, i'm not sure how to make the two libraries work together better.

Does not detect inheritance, adding resource fails

If added resource inherits from a super class and the methods (get, post, delete, etc.) are residing in the super class only, it does not detect to import the resource from super class for given endpoints.

Swagger doesn't play well with restful prefix

If I define a prefix in my restful initialization restful.Api(app, prefix='/api') the prefix doesn't pass along to swagger.
Consider something like this where I want everything that is Rest related to be exposed under the api.

api = swagger.docs(
    restful.Api(app, prefix='/api'),
    basePath='http://localhost:8080',
    apiVersion='0.1',
    api_spec_url='/spec',
)

Drop-down not auto-populating

I have a query parameter that accepts a boolean value.

In the generated swagger page the associated drop-down box is not populated with "True" or "False".

Large app best practice ?

First off, thanks for your work !

I'm trying to follow flask's Large-app-how-to to structure an API I would like to add Swagger support to. I'm pretty new to it and I'm not very confident about the way I'm using flask-restful-swagger with blueprints.

As of now, I'm simply repeating the swagger.docs call in every module

my_blueprint = Blueprint('my_blueprint', __name__)
api = swagger.docs(Api(my_blueprint), ...)

It seems to work but is it the right way to do it ?

Static files missing from MANIFEST.in

This is causing the static files to be left out when creating an .rpm with setuptools. To fix, simply add this to MANIFEST.in:

recursive-include flask_restful_swagger/static *

Also, love this package, thanks for your work!

you MUST specify a dataType for endpints

Hi, I just wanted to point out that not specifying a dataType for endpoint parameters will cause swagger.js to break and none of your endpoints will show up. Took me 2 hours to figure out, could you please point this out in the readme? Thanks!

urlparse is not available in python 3

$ python
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask_restful_swagger import swagger
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\proj\job-flow\venv\lib\site-packages\flask_restful_swagger\swagger.py", line 5, in <module>
    import urlparse
ImportError: No module named 'urlparse'
>>>

New example, please

Hi there!

I am just starting with flask and swagger. I would like to use an api_key for some methods that the clients will have to send for using them. I was not able to find documentation about this and I don't get it exploring the source code. Too much new information for me: flask, swagger, swagger-ui-js... so I don't know where to start to dig from to find the solution.

Could you extend some example to need an api_key (let's say api_key=token_test) to use it=

Thanks

spec.html only showing first blueprint registered

Trying to figure out what I have done wrong. I am registering 3 different blueprints into my app, but the spec.html page only ever shows the operations for whichever one I registered first. So in my example snippets here, only the operations from blueprint_1 end up in the spec.

blueprint_1.py

blueprint = Blueprint('blueprint_1', __name__)
api = swagger.docs(Api(blueprint), apiVersion='1.0', api_spec_url="/v1.0/spec", description="API Documentation")

blueprint_2.py

blueprint = Blueprint('blueprint_2', __name__)
api = swagger.docs(Api(blueprint), apiVersion='1.0', api_spec_url="/v1.0/spec", description="API Documentation")

blueprint_3.py

blueprint = Blueprint('blueprint_3', __name__)
api = swagger.docs(Api(blueprint), apiVersion='1.0', api_spec_url="/v1.0/spec", description="API Documentation")

app.py

app.register_blueprint(blueprint_1.blueprint, url_prefix='/api')
app.register_blueprint(blueprint_2.blueprint, url_prefix='/api')
app.register_blueprint(blueprint_3.blueprint, url_prefix='/api')

Swagger UI doesn't send POST requests when clicking Try It Out button

The "Try it out!" button sends GET requests properly, but not POST requests. Per wireshark sniffs, no data is set, meaning, it's not a matter of erroneous data. This seems to be the case where paramType is query, body or header. Other values for paramType not tested. It seems like the form submission code is defined in swagger-ui.js in the OperationView.prototype.submitOperation function, but it simply calls model["do"] which doesn't seem to be defined.

UnicodeDecodeError raised when retrieving static/images/*

Seeing the following error when requesting api/spec/_/static/images/pet_store_api.png...

Debugging middleware caught exception in streamed response at a point where response headers were already sent.
Traceback (most recent call last):
File "/home/robert/.virtualenvs/debug/lib/python3.4/site-packages/werkzeug/wsgi.py", line 691, in next
return self._next()
File "/home/robert/.virtualenvs/debug/lib/python3.4/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
for item in iterable:
File "/usr/lib/python3.4/codecs.py", line 313, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte

Blueprint url prefix bug

I noticed that the swagger endpoints do not work properly when the Api prefix is set instead of the Blueprint's url_prefix.

e.g.

# This does not work even though the routes are available
api = swagger.docs(Api(hw, prefix='/api/v1'), apiVersion='1.0', api_spec_url='/spec')
api.add_resource(HelloWorld, '/hello')
app.register_blueprint(hw)


# This does work
api = swagger.docs(Api(hw), apiVersion='1.0', api_spec_url='/spec')
api.add_resource(HelloWorld, '/hello')
app.register_blueprint(hw, url_prefix='/api/v1')

Port mismatch for resources

I have a Flask app using this Swagger integration behind an internal load balancer in EC2, which I'm accessing in my local browser through SSH port forwarding.

Effectively, this means I enter http://localhost:8070/api/spec.html to access the Swagger endpoint. The problem is that all the resources in that HTML are linking to http://localhost:80 explicitly e.g. http://localhost/api/spec/_/static/swagger-ui.js, which means that they can't be loaded.

Is there any particular reason to avoid relative URLs here?

Thanks

Support multiple api on the same flask app

I am trying to get the following to work:

app = Flask()

my_blueprint1 = Blueprint('my_blueprint1', __name__)
my_blueprint2 = Blueprint('my_blueprint2', __name__)

api1 = swagger.docs(
    Api(my_blueprint1), apiVersion='0.1',
    produces=["application/json"],
    api_spec_url='/spec')
api2 = swagger.docs(
    Api(my_blueprint2), apiVersion='0.2',
    produces=["application/json"],
    api_spec_url='/spec')

api1.add_resource(TodoList, '/todos')
api1.add_resource(Todo, '/todos/<string:todo_id>')
api1.add_resource(MarshalWithExample, '/marshal_with')
api2.add_resource(TodoList, '/todos')
api2.add_resource(Todo, '/todos/<string:todo_id>')

app.register_blueprint(my_blueprint1, url_prefix='/api1')
app.register_blueprint(my_blueprint2, url_prefix='/api2')

app.run(debug=True)

But only /api1/spec.json endpoint works and it includes the documentation for the other endpoint as well.

Do you have any ideas how I can make this work? Also it looks like swagger doesn't respect API prefixes so that static files are broken when using one. This has probably something to do with the basePath.

@rantav Would you accept a PR for that?

  • Register multiple blueprints using the same global variables
  • Deferred change of the basePath when a blueprint is initialized with a url_prefix
  • Deferred using a basePath until requested to support load balancers

Support typical swagger document structure

Hi, great project! Before I send any pull requests, I'd like to see if there's a way to implement the typical swagger document structure. It looks something like this:

/api-docs  <= resource listing, contains pointers to all apis in the service
/api-docs/{name} <= api declaration describing the {name} api

See references here:
https://github.com/wordnik/swagger-core/wiki/Resource-Listing
https://github.com/wordnik/swagger-core/wiki/API-Declaration

I see a couple other simple things to fix that will help produce JSON consumable by the swagger-codegen.

POST ContentHeaderType not set properly

I am having an issue where the POST Content Header is text.

Referer: http://localhost:5000/api/spec.html
Origin: http://localhost:5000
Content-Length: 0
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
Connection: keep-alive
Host: localhost:5000
Accept: application/json
Accept-Language: en-US,en;q=0.8
Content-Type: text/plain;charset=UTF-8
Accept-Encoding: gzip,deflate,sdch

I am just trying out the example.py file.

Not a bug - I'm saying Thank You

Hello Ran, this is a quick thank-you. I've been using Flask for years but never Swagger and my boss wanted our project documented with Swagger. I plugged into restful-swagger a few days ago, we've now got a nicely documented data science tool for easy consumption by non-Python developers (which sits on numpy and scipy).

Many thanks for building this up (and I hope your search for a new maintainer goes smoothly).

shipped swagger-ui has trouble with file uploads

My Resource has a file parameter defined this way:

        parameters=[
            {
                "name": "file",
                "description": "an image uploaded using multipart-formdata",
                "required": True,
                "allowMultiple": False,
                "dataType": "file",
                "paramType": "body"
            }]

When I'm trying to test my api using swagger-ui it doesn't work. The file parameter is not sent to my backend. It looks like the shipped swagger-ui code has some problems and according to google a newer version should fix this.
I also tried out @richtera's branch from #17 and this seems to fix the file upload problems.
any chance to upgrade the swagger-ui code to the latest version?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.