getsling / flask-swagger Goto Github PK
View Code? Open in Web Editor NEWA swagger 2.0 spec extractor for flask
License: MIT License
A swagger 2.0 spec extractor for flask
License: MIT License
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):
...
One idea would be to provide a directory path to swagger in which to search for definitions in docstrings of models
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!
Hi,
I have this broken out into a set of blueprints and was wondering how one would go about setting up JWT on top of flask-swagger. Any success, or is there an alternative suggestion?
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).
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! ๐
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 ?
Something like a flake8 plugin would be awesome :-)
Here is the question on StackExchange: https://softwarerecs.stackexchange.com/q/76683/1834
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!
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.
Maybe I'm doing something wrong and I haven't realize it, any thoughts?
Old Path: /timeclock/clockin
New path: /{org_id}/timeclock/clockin
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
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?
Currently, it seems we are looking for schema key under parameters as I trying to use resuableParams.
Any chance we can support it?
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.
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
Currently even though "securityDefinitions" section is provided in the documentation for the API, it is not reproduced in the final JSON produced.
@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")
Following definition should be present at the root level of the JSON generated.
"securityDefinitions": {
"BasicAuth": {
"type": "basic"
}
}
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"}}
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.
As per JSON Schema
schema:
id: "#/definitions/Bla"
properties:
bla:
type: string
description: Bla
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.
It should just swallow and ignore
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
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.
Currently only summary, description, tags, parameters and responses are supported.
Missing: operationId, consumes, produces, schemes, deprecated, security
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!
Will $ref work to a remote server. When i was attempting it seemed to insert '/' before the url but I was wondering if I am missing something else?
Are there plans to add type annotations or stub files for mypy?
I've written an article about type annotations if you need one :-)
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?
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.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.