Coder Social home page Coder Social logo

flask-swagger's People

Contributors

abhaga avatar atlithorn avatar brentthew avatar bryant1410 avatar ibratoev avatar jamesboehmer avatar krasmussen-godaddy avatar mikaeilorfanian avatar ninit avatar notjustpizza avatar ocaballeror avatar platonoff-dev avatar ramonvg avatar rochacbruno avatar steven-eardley avatar thanhson1085 avatar tyarkoni avatar wushaobo 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

flask-swagger's Issues

Make docs processor more configurable

To use markdown in my api docs, right now I use monkey patching like this:

import flask_swagger
import CommonMark

def sanitize(text):
    parser = CommonMark.DocParser()
    renderer = CommonMark.HTMLRenderer()
    ast = parser.parse(text)
    return renderer.render(ast)

flask_swagger._sanitize = sanitize

But this could be made a configurable parameter like:

def swagger(app, process_doc=_sanitize):
    ...

'base_path' argument error

I'm using flask-swagger-0.2.14
but when i ran the first example like in your README.md

@app.route("/spec")
def spec():
   base_path = os.path.join(app.root_path, 'docs')
   return jsonify(swagger(app), from_file_keyword="swagger_from_file", base_path=base_path)

@app.route('/test', methods=['POST'])
def login():
   """
   swagger_from_file: test.yml
   """

I got this error

swagger() got an unexpected keyword argument 'base_path'

Could you tell me how to resolve it!
Thank in advance!

Method/route combinations appear in swagger documentation output that are not in the code

Permutations of routes and methods appear as documented operations in the swagger output that aren't present in the code. Other applications rely on the JSON output of swagger, and the superfluity of operations breaks that.

mod.add_url_rule('/edges/', defaults={'annotation_id': None}, methods=['GET']) mod.add_url_rule('/edges/', methods=['POST']) mod.add_url_rule('/edges/<int:annotation_id>/', methods=['GET', 'PUT', 'PATCH', 'DELETE'])

i.e. The code defines a route at /edges/ with "GET" and "POST" methods. The code also defines a route at /edges/<int:annotation_id>/ with "GET", "PUT", "PATCH", and "DELETE" methods. [This is a total of 2 routes and 5 method verbs.] The swagger output shows a list of 10 operations, which includes combinations of verbs and routes that don't exist in code (e.g. "POST" for the /edges/<int:annotation_id>/ route, and "PUT" for the /edges/ route).

Add partial substitution of docstrings -- expansion of .yml file support

I was curious if there will be support for doing a partial substitution of a doc string instead of an entire replace if you specify a .yml file?

What I'm trying to do is something like:

def my_func():
    """
    My func title

    special text for my func

    swagger_from_file: file.yml

    more special text
    """

And have the special text for my func and more special text be represented as well. Currently the whole doc string gets replaced by what's in the file.yml file. This is especially useful when there's a bunch of endpoints with mostly common functionality but differ by a few parameters for example.

I'd be happy to make a PR for this if you see it as a worthy addition! ๐Ÿ˜„

AttributeError: type object 'Create' has no attribute 'lower'

I am using Flask-Swagger with Flask-MongoRest. Last versions, with Python 3.8.2.

I wanted to simply try this code from the README:

from flask import Flask, jsonify
from flask_swagger import swagger

app = Flask(__name__)

@app.route("/spec")
def spec():
    return jsonify(swagger(app))

then when I do GET http://127.0.0.1:5000/spec, the following error is displayed:

  File "/home/cedric/.cache/pypoetry/virtualenvs/stats-api-7Yf7ZOUq-py3.8/lib/python3.8/site-packages/flask_swagger.py", line 178, in <lambda>
    and verb in map(lambda m: m.lower(), endpoint.methods) \
AttributeError: type object 'Create' has no attribute 'lower'

I fixed my issue by changing this code:
https://github.com/gangverk/flask-swagger/blob/master/flask_swagger.py#L177-L179

to

if hasattr(endpoint, 'methods') \
                    and verb in map(lambda m: m.method.lower(), endpoint.methods) \	
                    and hasattr(endpoint.view_class, verb):

Since actually here m is an object, not a string. m.method is a string. It also works with str(m).lower().

With this change, it works quite well.

If you want I can create a fix which will works with m.lower() and m.method.lower() and make a pull request.

Or do you thing the issue is on the side of Flask-MongoRest ?

Forked

Hi, I forked it here: https://github.com/rochacbruno/flasgger
Added a demo app http://flasgger-rochacbruno.rhcloud.com/

As ai changed many things, included SwaggerUI embedded to the extension, changed from function to class based and blueprint based views.

So I did not sent a pull request yet.

Are you interested in merge? (we can keep backwards compatibility) or simply mention each extension on READMEs.

Thanks for the work!

Open Source Rocks!

Pip source code is different from github master branch

Hi, I installed flask-swagger using 'pip install flask-swagger' and I noticed the downloaded source code is different from the one published in the master branch. Notice "_parse_docstring" function on the left and "_find_from_file" on the right.

screenshot 2016-09-30 14 38 50

Maybe I'm doing something wrong and I haven't realize it, any thoughts?

Swagger UI v3

Hi

I tried out flask-swagger with Swagger UI v3, it looks like there's some minor incompatibility issues. Are there any plans to support v3, on a new fork. I'd be happy to help.

The biggest issue appears to be the addition of the requestBody section in place of the in: body section. Looking at the spec, I think after a cursory look everything else should be mostly compatible. famous last words :)

Thanks
Iain

Different documentation for each method of a endpoint

How would one go about adding different documentation for each method of the same endpoint?

For example, this code:

@app.route('/some/endpoint', methods=['PUT', 'GET'])
def some_path():
    """
    Some Endpoint
    ---
    tags:
        - some endpoint
    responses:
        200:
            description: success
    """
    (...)

will generate the same documentation for both PUT and GET methods.

How can I specify a particular definition for each method?

Passing Absolute YAML Path In Windows

Hi,
I am passing absolute path in doc string as below :
swagger_from_file: C:\Users\PriyankaAgarwal\repo2\example.yml
in doc string, but it is not detecting the file.
Reason: in flask_swagger.py, it splits using colon and check if array length after split is 2 , but here we get length as 3 so ,is there any other way to pass absolute path or modification to flask_swagger.py is needed to consider all part of that line after 1st colon as path.

Are Blueprint supported ?

Hi,

I have a Flask app using Blueprints and would like to document the API using swagger. I love the idea of having a single source of truth when it comes to the API documentation and hence would like to use flask-swagger.
Does it support Blueprint ?
I must admit I didn't even try, I was hoping to first get some tips before messing around with my docstrings everywhere....

thanks

Brieuc

Support for "securityDefinitions"

Currently even though "securityDefinitions" section is provided in the documentation for the API, it is not reproduced in the final JSON produced.

Sample Documentation on a API method (with securityDefinitions section)

@app.route('/reports', methods=["POST"])
def sample_meth():
       """
       Uploads the given file to servers.
        ---
        securityDefinitions:
          BasicAuth:
            type: "basic"
        definitions:
          - schema:
            id: ErrorResponse
            properties:
              error:
                type: "string"
                description: "Gives a description about the error."
            example:
              error: "Lab name is not provided."
        operationId: "uploadReport"
        security:
          - BasicAuth: []
        """
        print("sample meth")

Expected JSON response

Following definition should be present at the root level of the JSON generated.

"securityDefinitions": {
    "BasicAuth": {
      "type": "basic"
    }
  }

Actual JSON response

Carries only the security requirement for the corresponding path, and the 'securityDefinitions' section is missing.

{ 
   "definitions":{ 
      "ErrorResponse":{ 
         "example":{ 
            "error":"Lab name is not provided."
         },
         "properties":{ 
            "error":{ 
               "description":"Gives a description about the error.",
               "type":"string"
            }
         }
      }
   },
   "paths":{ 
      "/reports":{ 
         "post":{ 
            "security":[ 
               { 
                  "BasicAuth":[ 

                  ]
               }
            ],
            "summary":"Uploads the given file to servers."
         }
      }
   }
}

Current solution is to add it manually to the generated JSON object, like below:

from flask_swagger import swagger
@app.route("/spec")
def spec():
     swag_doc = swagger(app)
     swag_doc['securityDefinitions'] = {"BasicAuth": {"type": "basic"}}

Support top-level parameters and responses

I have a number of endpoints that have the same query parameters and responses; not the same schema, but the entire parameter/response is exactly the same. It would be great to use swagger's top-level parameters and responses objects and reference them from the YAML decorating my views, much like we can now do with schema definitions.

Currently, I can define the parameters object on the swag object, but if I try to reference it in my YAML, it just gets converted to null.

TypeError: swagger() got an unexpected keyword argument 'base_path'

I am using flask-swagger(0.2.14) installed via pip.
There is a problem setting 'base_path' in swagger().

swag = swagger(app, from_file_keyword="swagger_from_file", base_path=base_path)

I've noticed that the following script in flask_swagger.py:

def swagger(app, prefix=None, process_doc=_sanitize,
            from_file_keyword=None, template=None):

Is there any update that is not available in pip?
Also, your latest commit is 12 May, and last pypi update is last year.

yaml file location

Hi,

what is the right location for the yaml files for the 'from_file_keyword'? IMHO it looks like I have to name the absolute location. What if I want to ship them as a package?

cheers,
Martin

pip install missing packages

I am using python 3.6, and after I run pip install flask-swagger, I only see flask_swagger-0.2.13.dist-info directory created under my site-packages, while the flask_swagger directory is missing.

Support all Operation fields

Currently only summary, description, tags, parameters and responses are supported.

Missing: operationId, consumes, produces, schemes, deprecated, security

Doc example showing root level definitions?

Would it be possible to provide documentation as how one would use root-level definitions? In the current examples the definitions are implemented per path or operation object.

I'd like to keep my definitions similar to the Petstore example, at the root level of the spec so they can be referenced by multiple paths/operation objects. Is that possible with flask-swagger?

Thanks!

Parser adding extra routes?

I have a class as follows:

class Docker(Resource):
    def post(self) -> "http response":
        """
        valid swagger docstring here
        """
        ...

    def get(self, session_id : str) -> "http response":
        ...

    def delete(self, session_id : str) -> "http response":
        ...

However, using your flask-swagger, TWO paths show up in resources:

Paths
/Docker
POST /Docker
/Docker/{session_id}
POST /Docker/{session_id}

The second path does not exist. What is happening?

Multiple path parameters and multiple endpoints

Hi there,

I currently have a flask_restful Resource with 2 path parameters: one compulsory, and one optional. I followed this recommendations of writing it this way:

api.add_resource(ProductsResource, '/products/<string:slug>', '/products/<string:slug>/<string:color>')

class ProductsResource(Resource):
      @marshal_with(products_fields)
      def get(self, slug, color=None):
           ....

Then, i have the following YML documentation in the docstring regarding parameters:

...
- name: slug
   in: path
   description: product's slug
   type: string
   required: true
- name: color
   in: path
   description: product's color
   type: string
   required: true

When I go to my project on http://localhost:5000/spec, I see that I have 2 endpoint generated:

But, for both endpoints there are those 2 required parameters, resulting in a swagger error: Path parameter is defined but is not declared: color.

Do you think it would be possible to filter the path parameters based on the endpoints used ? Here it would mean filter out 'color' for the first endpoint.

Thanks,
Pierre.

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.