pyeve / eve-swagger Goto Github PK
View Code? Open in Web Editor NEWSwagger extension for Eve-powered RESTful APIs
Home Page: http://python-eve.org
License: Other
Swagger extension for Eve-powered RESTful APIs
Home Page: http://python-eve.org
License: Other
There is a lot of info that is not available in Eve and yet is needed for Swagger. The current approach is that the settings can be expanded with a SWAGGER
document which includes all the extra data. I am not sure this is the best approach.
Maybe we could just add support new keywords in the settings file, eventually prepended by the SWAGGER
title, very much like the MONGO
prefix( e.g. API_TITLE
or SWAGGER_API_TITLE
). This would also come in handy at a later stage, when we're working on resources ("paths" in swagger terms). Iterating through the DOMAIN
would allow to retrieve both eve standard settings and swagger's if available, instead of having to look at two different places during the whole process. Would probably be easier on the user too, as all resource configuration is held at one place.
pip install eve-swagger
Collecting eve-swagger
Using cached Eve-Swagger-0.0.2.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-lzr7ya90/eve-swagger/setup.py", line 7, in
VERSION = import('eve_swagger').version
File "/tmp/pip-build-lzr7ya90/eve-swagger/eve_swagger/init.py", line 10, in
from swagger import swagger # noqa
ImportError: No module named 'swagger'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-lzr7ya90/eve-swagger/
Hello,
I would like to have geographic data types support :
Regards,
dabos
is this support gridfs file API ?
for download and import file
Eve has an X_DOMAINS configuration option to specify which domains will be allowed Cross Origin access to one's API endpoints. It would be great if Eve Swagger could honor this configuration so the Swagger config can be loaded via a URL in the Swagger UI
I think it's pretty to have all fields of a resource (from the schema) and display it in swagger-ui (so in json). Like this, for post command we can have information. (refer to eve-docs display style ;) )
I have python-eve behind an nginx reverse proxy, served at /api
rather than /
. However, the execution links in the basePath generated by eve-swagger is taken from URL_PREFIX, so excludes the /api
and simply returns /
.
This means that the Swagger UI does not work when executing the requests. Unfortunately, SwaggerUIBundle does not support setting a custom baseRef. I have solved this by declaring a new swagger route and hardcoding the basePath, however it seems like this is a common production use-case, so I'm wondering if there is a better way of achieving this?
Incidentally, on the Eve side, the paths are handled with this Flask snippet.
With 0.0.1 I get a AttributeError: 'module' object has no attribute 'name' error
when trying to register the Blueprint.
people = {
'item_lookup_field': 'name',
'item_title': 'person',
'schema': {...}
}
Currently the path parameters are named like /people/{personId}
. To me it would seem more logical to name the parameter after the field name that is used for lookup, i.e. /people/{name}
.
Without a custom item_lookup_field
that would result in /people/{_id}
though...
See https://swagger.io/docs/specification/2-0/adding-examples/
The description field is already supported, it would be nice to also support the example
field in schema. This would make swagger-ui provide ready to use data in requests.
If an endpoint supports versioning should the Swagger UI provide an optional query parameter to allow users to request different versions of a document?
Of course it's a little bit more complex, since any resource could overwrite the global configuration.
I'm planning to submit PR's soon to solve this issue.
Hi,
I am using eve-sqlalchemy as db-manager and the output generated by eve-swagger contains nullable attributes, which is not supported by Swagger 2.0.
My model is something like:
class MyModel():
__tablename__ = "mymodel"
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String(256))
And the output generated contains:
definitions:
MyModel:
type: object
properties:
id:
nullable: false
type: integer
title:
maxLength: 256
nullable: true
type: string
Note: I have seen the issue #39, but its closed and I don't know if he was using also eve-sqlalchemy.
Any idea to avoid this?
Thanks!
I have enabled BasicAuth in py-eve which works properly.
I have also just installed eve-swagger which also mostly works.
If I use the Try It Out button,
Then perform Execute, it is obviously missing my authorization header.
https://swagger.io/docs/specification/authentication/basic-authentication/
Shows how to configure it normally, just not sure how to do it through eve-swagger.
Thanks in advance!
It should have been there right from the start 😈
Swagger UI will not allow PUT/PATCH/DELETE without an If-Match header, even when concurrency control is disabled in the API.
In my settings for my api I have the following:
IF_MATCH = False
ENFORCE_IF_MATCH = False
I have also tried removing the header from X_HEADERS:
X_HEADERS = ['Authorization', 'Content-Type', 'Accept']
I have verified that I can PUT/PATCH/DELETE objects via the REST API, but the swagger ui will not allow the 'Try it now' option without supplying an If-Match header.
Converting Eve to Swagger is cool.
But it would be even cooler to support Swagger natively.
I found it's a little bit cumbersome to work with Eve when you go with API design first approach.
If you use services like APIMATIC or SwaggerHub, you can design API there and then produce machine readable config like swagger. It would be nice if I can import it in Eve somehow, so I don't need to sync changes manually every time.
Of course I can design using Eve, but if I need to collaborate with other people it becomes problematic.
Connexxion is implementing this approach btw https://github.com/zalando/connexion
When will eve-swagger support securityDefinitions?
I have added following Flask routes with authentication enabled. Authenticate class is defined appropriately. Basic auth working on all endpoints including /docs but when I access /static/index.html directly, basic auth doesn't work.
What am I missing here?
app = Eve(__name__, static_folder='static', auth=Authenticate)
@app.route('/docs')
@utils.requires_auth
def docs():
return redirect('/static/index.html', code=301)
@app.route('/')
@utils.requires_auth
def index():
return send_from_directory('static', 'index.html')
Hi,
The JSON that is generated doesnt appear to be compatible when your schemas have fields with "default: None". I know that this is more of a shortcoming of the Swagger spec itself, but is there something on the Eve-Swagger side that can be done to address this other than excluding the offending schema from being documented?
Can you please tell me how to make the swagger doc clearly display the POST request and response body separately?
For example, suppose I want to implement a POST /myobject with 'input' in the request body and 'output' in the response body. How do I specify this so that swagger distinguishes between them?
I have the following in my settings.py:
DOMAIN = {
'myobject': {
'extra_response_fields': ['input', 'output'],
'schema': {
'input': {'type':'string'},
'output': {'type':'string'}
}
}
}
The resulting swagger doc when viewing through petstore shows the request body with both the 'input' and 'output' fields, but it does not show a response body.
{
"input": "string",
"output": "string",
"_id": "string"
}
Thanks in advance for the help,
Keith
I wrote a REST-API and all of the domains are accessible but not api-docs (it gives me the internal server error). I followed the instruction that posted in the first page but it doesn't work. Do I need to add something into my settings.py file? Do I need to define api-docs as a domain?
When using sub-resources (http://python-eve.org/features.html#sub-resources) you probably have this kind of url: 'people/<regex("[a-f0-9]{24}"):contact_id>/invoices'
This syntax "conflicts" with the Swagger path params which are defined using brackets {
. Then it considers that 24
is a path params, but not contact_id
.
I'm not sure what would be the right approach for this problem, maybe rewrite urls to have something like people/{contact_id}/invoices
and a swagger path definition like
{
"name": "contact_id",
"in": "path",
"description": "regex("[a-f0-9]{24}")",
"required": true,
"type": "string"
}
Which means that now the test suites fails on Py26 environment
stale-bot looks like a useful tool to keep tickets under control and manageable. The rationale is as follows (quoting from the repository README):
In an ideal world with infinite resources, there would be no need for this app.
But in any successful software project, there's always more work to do than people to do it. As more and more work piles up, it becomes paralyzing. Just making decisions about what work should and shouldn't get done can exhaust all available resources. In the experience of the maintainers of this app—and the hundreds of other projects and organizations that use it—focusing on issues that are actively affecting humans is an effective method for prioritizing work.
To some, a robot trying to close stale issues may seem inhospitable or offensive to contributors. But the alternative is to disrespect them by setting false expectations and implicitly ignoring their work. This app makes it explicit: if work is not progressing, then it's stale. A comment is all it takes to keep the conversation alive.
current master adds the API_VERSION path segment to the url, but it doesn't add the URL_PREFIX
Hi,
what about mapping the index endpoint on the /
route instead of /api-docs
letting the embedding app to map wherever it likes with url_prefix
?
diff --git a/eve_swagger/swagger.py b/eve_swagger/swagger.py
index e90f374..0b5941c 100644
--- a/eve_swagger/swagger.py
+++ b/eve_swagger/swagger.py
@@ -81,7 +81,7 @@ def _modify_response(f):
return decorated
[email protected]('/api-docs')
[email protected]('/')
@_modify_response
def index():
def node(parent, key, value):
If I submitted such a PR, would it get accepted or are there any reason not doing so in the first place?
Best regards,
Patrick.
Tests import from flask_pymongo, which used to be an Eve dependency. This is not the case anymore, so now tests are failing because of a failed import.
Like we did with pyeve/eve#1143. Readability should greatly improve
I saw that you can add a special query param like this:
add_documentation({'paths': {'/status': {'get': {'parameters': [
{
'in': 'query',
'name': 'foobar',
'required': False,
'description': 'special query parameter',
'type': 'string'
}]
}}}})
But I'm wondering if I'm missing how to define parameters in the DOMAIN dict. Shouldn't there be a way to add them right there?
Following the current Python Eve documentation, there's an error http response status next to the success response (201)
When all documents pass validation and are inserted correctly the response status is 201 Created. If any document fails validation the response status is 422 UnprocessableEntity
Is it possible to add this error status to the documentation per default? Listing all possible error codes (like 404 or 401) may be too much, but 422 should show up in the documentation. Also mind the option to override this status code with the VALIDATION_ERROR_STATUS setting.
I would like to force my Swagger UI to use https
only. I tried to update my Swagger definition:
add_documentation({
'schemes': ['https'],
})
but in my Swagger UI I can still see a drop-down menu with both http
and https
.
Can I do this by updating my definition or should I handle it "manually" in my Swagger UI?
Swagger Online Editor, http://editor2.swagger.io generates error on JSON generated.
Swagger Error
Not a valid parameter definition
Jump to line 616
Details
Object
code: "ONE_OF_MISSING"
params: Array [0]
message: "Not a valid parameter definition"
path: Array [2]
0: "parameters"
1: "business__id"
schemaId: "http://swagger.io/v2/schema.json#"
inner: Array [2]
0: Object
code: "OBJECT_MISSING_REQUIRED_PROPERTY"
params: Array [1]
message: "Missing required property: schema"
path: Array [2]
0: "parameters"
1: "business__id"
1: Object
code: "ONE_OF_MISSING"
params: Array [0]
message: "Data does not match any schemas from 'oneOf'"
path: Array [2]
inner: Array [4]
level: 900
type: "Swagger Error"
Line 616 is in the "parameters:" definition area. Each parameter defined generated same error.
business__id:
in: path
name: businessId
required: true
description: ''
example: ''
type: string
format: objectid
business__id is referenced in this path definition and the parameter line is flagged with same error:
patch:
summary: Updates a business document
responses:
'200':
description: business document updated successfully
parameters:
- $ref: '#/parameters/business__id'
- in: body
name: business
required: true
schema:
$ref: '#/definitions/business'
- in: header
name: If-Match
description: Current value of the _etag field
required: true
type: string
tags:
- business
I am thinking about a feature that allows the user to add a description to specific HTTP methods of a resource.
people = {
'method_description': {
'GET': 'If you send a GET request to the /people endpoint, then foobar',
'GET_item': 'A request for one person activates a hook that does something',
'DELETE': '...'
},
'schema': {...}
}
The descriptions would show up in the swagger doc under the correct paths (/people: {get: {description: ...}}
) additionally to the summary ("Retrieves one or more people") that is already there.
I am happy to implement this feature if you think it is useful.
i am unable to get eve- swagger to work with my eve-mongoengine/eve app.
my code looks like this
`from eve import Eve
from eve_mongoengine import EveMongoengine
from eve_swagger import swagger, add_documentation
from models import *
all = (
'create_connection', 'disconnect', 'get_connection',
'DEFAULT_CONNECTION_NAME', 'fetch_connection_settings',
'InvalidSettingsError', 'get_db'
)
DEFAULT_CONNECTION_NAME = 'default-mongodb-connection'
MONGODB_SETTINGS = {
'MONGO_HOST': 'localhost',
'MONGO_PORT': 27017,
# 'MONGO_USERNAME' : None,
# 'MONGO_PASSWORD': None,
'MONGO_DBNAME': 'ashrm3',
'X_DOMAINS': '*',
'ALLOW_OVERRIDE_HTTP_METHOD':'true',
'JSON_SORT_KEYS ':'true',
'DOMAIN': {'in': {}},
}
app = Eve(settings=MONGODB_SETTINGS)
ext = EveMongoengine(app)
app.register_blueprint(swagger)
app.config['SWAGGER_INFO'] = {
'title': 'My Supercool API',
'version': '1.0',
'description': 'an API description',
'termsOfService': 'my terms of service',
'contact': {
'name': 'nicola'
},
'license': {
'name': 'BSD'
}
}
ext.add_model([Item,MessageThreads,Messages])
app.run(host='127.0.0.1', port=8001,debug=True)`
full stack trace
File "/Users/Omkareshwar/PycharmProjects/apid/apid/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Omkareshwar/PycharmProjects/apid/apid/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functionsrule.endpoint
File "/Users/Omkareshwar/PycharmProjects/apid/apid/lib/python2.7/site-packages/eve_swagger/swagger.py", line 38, in decorated
resp = make_response(f(*args, **kwargs))
File "/Users/Omkareshwar/PycharmProjects/apid/apid/lib/python2.7/site-packages/eve_swagger/swagger.py", line 101, in index
node(root, 'parameters', parameters())
File "/Users/Omkareshwar/PycharmProjects/apid/apid/lib/python2.7/site-packages/eve_swagger/objects.py", line 76, in parameters
eve_type = rd['schema'][lookup_field]['type']
KeyError: '_id'
my requirements.txt looks like this
blinker==1.4
Cerberus==0.9.2
Eve==0.4
Eve-Mongoengine==0.0.9
Eve-Swagger==0.0.5
Events==0.2.1
Flask==0.10.1
flask-mongoengine==0.8
Flask-PyMongo==0.4.1
Flask-WTF==0.13.1
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
mongoengine==0.10.6
pymongo==3.2.1
simplejson==3.8.2
Werkzeug==0.11.4
WTForms==2.1
The POST should be generated with the adequate content-type and the fields should be documented as files.
I'll do some research and try to submit a PR soon.
The dynamic swagger documentation was split from index_json into its own function, however there hasn't been a release since this change was made last year. So far I'm getting by installing via github, but an official release would be nicer.
This is the function:
eve-swagger/eve_swagger/swagger.py
Line 60 in 89adbd1
I'm building support to have flasgger/flasgger#316 (serves Swagger UI) consume this generated swagger at runtime and display swagger docs.
when i add example
and description
to schema, I can not pass validate,
according to docs, I should use TRANSPARENT_SCHEMA_RULES
in settings, but this variable is deleted from eve
File "/Users/jove/work/python3/lib/python3.7/site-packages/cerberus/validator.py", line 169, in __init__
self.schema = kwargs.get('schema', None)
File "/Users/jove/work/python3/lib/python3.7/site-packages/cerberus/validator.py", line 509, in schema
self._schema = DefinitionSchema(self, schema)
File "/Users/jove/work/python3/lib/python3.7/site-packages/cerberus/schema.py", line 69, in __init__
self.validate(schema)
File "/Users/jove/work/python3/lib/python3.7/site-packages/cerberus/schema.py", line 197, in validate
self._validate(schema)
File "/Users/jove/work/python3/lib/python3.7/site-packages/cerberus/schema.py", line 219, in _validate
raise SchemaError(self.schema_validator.errors)
cerberus.schema.SchemaError: {'hostname': [{'description': ['unknown rule'], 'example': ['unknown rule']}], 'idc': [{'description': ['unknown rule'], 'example': ['unknown rule']}], 'interfaces': [{'description': ['unknown rule'], 'schema': ['no definitions validate', {'anyof definition 0': [{'schema': [{'eth': ['unknown rule'], 'ip': ['unknown rule'], 'mac': ['unknown rule']}], 'type': ['null value not allowed']}], 'anyof definition 1': [{'schema': ['no definitions validate', {'anyof definition 0': [{'eth': [{'example': ['unknown rule']}], 'ip': [{'example': ['unknown rule']}], 'mac': [{'example': ['unknown rule']}]}], 'anyof definition 1': [{'eth': ['unknown rule'], 'ip': ['unknown rule'], 'mac': ['unknown rule']}]}]}]}]}], 'source': [{'description': ['unknown rule']}]}
When import eve-swagger in python3
Traceback (most recent call last):
File "/usr/local/bin/alignak_backend", line 9, in <module>
load_entry_point('alignak-backend', 'console_scripts', 'alignak_backend')()
File "/usr/local/lib/python3.4/site-packages/pkg_resources/__init__.py", line 547, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "/usr/local/lib/python3.4/site-packages/pkg_resources/__init__.py", line 2720, in load_entry_point
return ep.load()
File "/usr/local/lib/python3.4/site-packages/pkg_resources/__init__.py", line 2380, in load
return self.resolve()
File "/usr/local/lib/python3.4/site-packages/pkg_resources/__init__.py", line 2386, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "/Donnees/developpement/sources/Alignak-monitoring/alignak-backend/alignak_backend/main.py", line 6, in <module>
from alignak_backend.app import app
File "/Donnees/developpement/sources/Alignak-monitoring/alignak-backend/alignak_backend/app.py", line 31, in <module>
from eve_swagger import swagger
File "/usr/local/lib/python3.4/site-packages/eve_swagger/__init__.py", line 10, in <module>
from swagger import swagger # noqa
ImportError: No module named 'swagger'
I've defined resources that contains other resources and when run eve server with eve-swagger enabled, this exception is raised:
[2017-09-13 15:55:17,566] ERROR in app: Exception on /api-docs [GET]
Traceback (most recent call last):
File "./flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "./flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "./flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "./flask/_compat.py", line 33, in reraise
raise value
File "./flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "./flask/app.py", line 1598, in dispatch_request
return self.view_functionsrule.endpoint
File "./eve_swagger/swagger.py", line 38, in decorated
resp = make_response(f(*args, **kwargs))
File "./eve_swagger/swagger.py", line 100, in index
node(root, 'definitions', definitions())
File "./eve_swagger/definitions.py", line 19, in definitions
dr_sources.update(_get_dr_sources(rd['schema']))
File "./eve_swagger/definitions.py", line 167, in _get_dr_sources
if rules.get('type') in 'dict':
TypeError: 'in ' requires string as left operand, not NoneType
Line 167 of definitions.py seemed weird to me. I've edited the line to be:
if rules.get('type') is 'dict':
I used 'is' operator instead of 'in' and it worked pretty well.
I filed an issue some days ago and it's closed now because it seemed to be not relevant. Maybe this issue is related to that one here because the stack trace of exception looks familiar to me:
#50
If you fix it, I can test it and it can be a fix for two issues!
Please correct it if it's a bug.
Thank you in advance
Hi,
I am using eve-sqlalchemy as db-manager and the output generated by eve-swagger contains the example attribute inside parameters, which is not supported by Swagger 2.0.
And the output generated contains:
parameters:
Mymodel:
in: path
name: alertId
required: true
description: ''
example: ''
type: integer
Any idea to avoid this?
Thanks!
Hey,
is it possible to load an existing swagger configuration into eve, and just define the hooks?
Isn't the proper way to define floats as:
type: number
format: float
rather than:
type: float
in the swagger docs?
I get validation errors on the generation swagger api in my tests.
The Eve-Mongoengine is a python library used to import mongoengine models into eve:
https://github.com/MongoEngine/eve-mongoengine
I had eve and eve-swagger working together fine. After I tried to install Eve-Mongoengine in my virtualenv, the eve-swagger produced an internal error when I tried to visit /api-docs endpoint. I've realized that there must be some version conflict between eve-swagger and Eve-Mongoengine that makes problems. It's output of eve when I tried to get /api-docs endpoint:
127.0.0.1 - - [28/Aug/2017 10:31:46] "GET /api-docs HTTP/1.1" 500 -
I tried eve in DEBUG mode and got nothing.
It's is my requirements.txt file before installing Eve-Mongoengine that was fine:
Cerberus==0.9.2
click==6.7
Eve==0.7.4
Eve-Swagger==0.0.7
Events==0.2.2
Flask==0.12
Flask-PyMongo==0.5.1
itsdangerous==0.24
Jinja2==2.9.6
MarkupSafe==0.23
pymongo==3.5.0
simplejson==3.11.1
Werkzeug==0.11.15
This is my requirements.txt after installing Eve-Mongoengine that makes /api-docs unavailable:
blinker==1.4
Cerberus==0.7.2
click==6.7
Eve==0.4
Eve-Mongoengine==0.0.9
Eve-Swagger==0.0.7
Events==0.2.1
Flask==0.10.1
Flask-PyMongo==0.3.0
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
mongoengine==0.13.0
pymongo==2.7.1
simplejson==3.5.2
six==1.10.0
Werkzeug==0.9.6
I am going to report this issue in Eve-Mongoengine git project.
if I paste the json form /api-docs to http://editor.swagger.io/#/ with the new v0.0.5, swagger editor complains about the json.
I guess v0.0.5 breaks swagger ui/editor?
Like in the eve-docs extension, only the label should be in the docs for custom resource urls on related data. For instance,
/model1/<regex("[a-f0-9]{24}"):model1_id>/model2
in the docs should be:
/model1/model1_id/model2
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.