Git Product home page Git Product logo

swagger-ui-py's People

Contributors

4d1l avatar b3n4kh avatar carstencodes avatar flying-sheep avatar giuliano-macedo avatar klaashoekstra94 avatar pasqlisena avatar patleg avatar pwzer avatar sdvallejo avatar tamarmot 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

Watchers

 avatar  avatar  avatar

swagger-ui-py's Issues

Configuration options for custom CSS

In addition to the existing options to configure SwaggerUI itself via its parameters, it would be great to have the ability to add custom CSS as well (https://github.com/ostranme/swagger-ui-themes for instance seems fairly popular).

From my point of view it would be enough to provide an additional <link> tag with href being populated from a config parameter (if defined) after

<link rel="stylesheet" type="text/css" href="{{ url_prefix }}/static/index.css" />

The content served at the route could then easily be managed by the user, something like (pseudo)

api_doc(app, config_path='./config/test.yaml', url_prefix='/api/doc', custom_css='/static/custom.css')

@app.route('/static/custom.css')
def custom_css():
    css = 'h1 { color: blue; }'
    return Response(css, mimetype='text/css')

What do you think? Would be willing to contribute a PR for this.

Add Swagger UI for bottle

Hey there,

I just got in touch with this cool package. I'm currently working on a small project with the bottle-py API.

It was little work to create an implementation for bottle using a simple specialization of the Interface class:

class BottleInterface(Interface):

    def __init__(self, *args, **kwargs):
        kwargs['app_type'] = 'bottle'
        super(BottleInterface, self).__init__(*args, **kwargs)

    def _bottle_handler(self):
        app = self._app

        @app.get("/")
        def index():
            return self.doc_html

        @app.get('/<filepath:re:.*\.(js|css)>')
        def java_script_file(filepath):
            return static_file(filepath, root=self.static_dir)

        @app.get("/swagger.json")
        def config_handler():
            from bottle import redirect
            # If bottle runs with the python 3.6 built-in wsgi-server, the sub-request will cause the wsgi server to fail the request, so redirecting will work. The host most be set in the config.
            redirect(self._config_url)

        if self._editor:
            @app.get("/editor")
            def editor():
                return self.editor_html

    def _auto_match_handler(self):
       try:
            from bottle import Bottle
            if isinstance(self._app, Bottle):
                  return self._bottle_handler()
        except:
             pass

        return super(BottleInterface, self)._auto_match_handler()

Is there a chance, that this might find a way to the next release?

Cannot add swagger ui to a flask blueprint

A blueprint should, for most purposes be indistinguishable from an application, and I think it makes perfect sense to have, say, a flask blueprint for an API, and add a swagger UI to that.

However, the flask handler contains this check:

    import flask
    if isinstance(doc.app, flask.Flask):
        return handler

Which fails, because flask.Blueprint is not a subclass of flask.Flask.

Perhaps the test should be:

    import flask.scaffold import Scaffold
    if isinstance(doc.app, Scaffold):
        return handler

Or perhaps it's safer like this as scaffold doesn't appear to be a documented part of the API:

    import flask
    if isinstance(doc.app, (flask.Flask, flask.Blueprint)):
        return handler

Support for self-signed certificate

Hey -

Is there a way for swagger-UI to support self-signed/local SSL certificates (aka request.get(xxx,verify=False) ?

This is the error I am getting when trying to deploy my API

File .../python3.7/site-packages/swagger_ui/core.py", line 75, in get_config
    with urllib.request.urlopen(self._config_url) as config_file:
  File ".../python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File ".../python3.7/urllib/request.py", line 525, in open
    response = self._open(req, data)
  File ".../python3.7/urllib/request.py", line 543, in _open
    '_open', req)
  File "...//urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "...//python3.7/urllib/request.py", line 1360, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File ".../python3.7/urllib/request.py", line 1319, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1051)>

bug: Swagger 3.0.0 datetime

When I try to create object with date-time I got

Fetch error
Internal Server Error /swagger.json

My simple app:

import falcon
import swagger_ui
from wsgiref import simple_server

app = falcon.API()
swagger_ui.falcon_api_doc(
    app, config_path="./swagger.yaml", url_prefix="/", title="API doc planed",
)

with simple_server.make_server('', 8000, app) as httpd:
    httpd.serve_forever()

specification:

openapi: 3.0.0
info:
  version: 1.0.0
  title: Example
  contact:
    email: [email protected]
servers:
  - url: http://localhost:8000
paths:
  "/":
    get:
      summary: Minimal example
      responses:
        "200":
          description: successful operation
components:
  schemas:
    Revision:
      type: object
      properties:
        revisionId:
          type: integer
          description: Monotonic revision ID, starting from zero
          example: 0
        created:
          type: string
          format: date-time
          description: Timestamp of the creation of this section
          example: 2019-02-01T17:23:11.683Z

Without that created property it works fine. I check that swagger.yaml is valid in many tools.

Disable Validator Option in Swagger object

Hello,
Could you please add an option to disable the validator url. As my Tornado application and schema looks fine and i get all the endpoints displayed in the UI but i get this weird error at the bottom maybe cause I'm not hosting any of the schema's.

image
Clicking on the invalid warning, gives an error like this
{"schemaValidationMessages":[{"level":"error","message":"Can't read from file http://xx.xx.xx.xx/api/doc/swagger.json"}]}

Currently i'm bypassing this error by adding the validatorUrl: null in the swagger object of doc.html, by following this thread swagger-api/swagger-ui#2796

Thanks

AttributeError: 'PosixPath' object has no attribute 'rstrip'

Hello,
I am recently facing this error when using swagger-ui.

Traceback (most recent call last):
  File "app/project.py", line 14, in <module>
    api_doc(app, config_path='swagger.yml', url_prefix='', title='Topic Model API')
  File "/usr/local/lib/python3.7/site-packages/swagger_ui/core.py", line 36, in __init__
    self._auto_match_handler()
  File "/usr/local/lib/python3.7/site-packages/swagger_ui/core.py", line 273, in _auto_match_handler
    return self._flask_handler()
  File "/usr/local/lib/python3.7/site-packages/swagger_ui/core.py", line 122, in _flask_handler
    static_folder=self.static_dir, static_url_path='/'
  File "/usr/local/lib/python3.7/site-packages/flask/blueprints.py", line 187, in __init__
    self.static_folder = static_folder
  File "/usr/local/lib/python3.7/site-packages/flask/helpers.py", line 1004, in static_folder
    value = value.rstrip("/\\")
AttributeError: 'PosixPath' object has no attribute 'rstrip'

I use swagger_ui in this way:

from swagger_ui import api_doc

app = Flask(__name__)
CORS(app)
api_doc(app, config_path='swagger.yml', url_prefix='', title='Topic Model API')

Trying to understand the problem, I am seeing that self.static_dir is indeed a PosixPath.
The problem is solved inserting in core.py@line120 the cast to str:

swagger_blueprint = Blueprint(
            'swagger_blueprint', __name__, url_prefix=self._url_prefix,
            static_folder=str(self.static_dir), static_url_path='/'
        )

Update swagger-ui to 5.0.0

Swagger-ui 5.0.0 has been released two months ago and adds support for OpenAPI spec 3.1.0 which adds a lot of improvements to complex types.

swagger-ui-py >="21.9.28" adds the "/api/doc/" on every URL of an api call

Hi, first let me thank your for coming up with this lib ;)

And before coming to the issue, here are my env settings:

python = 3.9
quart = "0.16.1"
quart-cors = "0.5.0"
swagger-ui-py = "21.9.28"
quart-openapi = "1.7.2"

I am generating the swager.json using quart-openapi and here is how my code looks like:

from quart import request, abort, jsonify
from quart_cors import cors
from quart_openapi import Pint, Resource
from swagger_ui import quart_api_doc

app = Pint(__name__, no_openapi=True)
app = cors(app, allow_origin="*")

@app.route("/api/doc/swagger.json")
async def openapi():
    return jsonify(app.__schema__)

quart_api_doc(
    app,
    config_url="http://localhost:8080/api/doc/swagger.json",
    url_prefix="/api/doc/",
    title="API doc",
    editor=True
)

@app.route("/sites")
class SitesInfoRequest(Resource):
    async def get(self):
        response = await get_all_sites_info()
        return jsonify(response), 200

....

when I run the project, locally, and access the url : http://localhost:8080/api/doc/, the page is generated correctly, with all the endpoints I created. The problem is, once I try out one of the endpoints, the URL that the page tries to hit is incorrect.

Instead of trying http://localhost:8080/sitesit is trying http://localhost:8080/api/doc/swagger.json/sites and I cant figure out what settings shall modify to make it work again.

[EDIT]
I did a bit of a research and found out that the problem only occurs from version 21.9.27.post1 on; on versions 21.9.27 and below, it still works as expected. I hope this helps finding the issue...

Thanks!

flask blueprint naming clash

I haven't tested this with other handler integrations but in the flask integration, because the Blueprint is created with a hardcoded name "swagger_blueprint", you can't add ui more than once (e.g. if you have have multiple specifications for different versions), because each Blueprint must have a unique name.

It would be nice if the name was derived from the ApplicationDocument.title or ApplicationDocument.url_prefix, so it can be set per document if needed.

Always get AssertionError or KeyError in aiohttp

I'm using this in aiohttp like:

    api_doc(
        app,
        config_path=(current_dir / "openapi.yaml").as_posix(),
        url_prefix='/',
        title="IAO API"
    )

And the server starts up fine.

But when I visit /. I get:

ERROR:aiohttp.server:Error handling request
Traceback (most recent call last):
  File "/nix/store/xw8zl3qcl8zha6wi7fns5rzmz2p1mqim-python3.7-aiohttp-3.6.2/lib/python3.7/site-packages/aiohttp/web_protocol.py", line 418, in start
    resp = await task
  File "/nix/store/xw8zl3qcl8zha6wi7fns5rzmz2p1mqim-python3.7-aiohttp-3.6.2/lib/python3.7/site-packages/aiohttp/web_app.py", line 458, in _handle
    resp = await handler(request)
  File "/nix/store/b93vasrvq42s3nhvrhlkjlaz55ji6qn0-python3.7-swagger-ui-py-0.3.0/lib/python3.7/site-packages/swagger_ui/core.py", line 154, in swagger_config_handler
    return web.json_response(self.get_config(request.host))
  File "/nix/store/b93vasrvq42s3nhvrhlkjlaz55ji6qn0-python3.7-swagger-ui-py-0.3.0/lib/python3.7/site-packages/swagger_ui/core.py", line 78, in get_config
    for server in config['servers']:
KeyError: 'servers'

And also:

image

Set the landing page to root `/`

When I try to setup swagger to serve the UI from root / (rather than /api/docs):

api_doc(app, config_path='swagger.yml', url_prefix='', title='API title')

I get the following error:

Traceback (most recent call last):
  File "app/run.py", line 1, in <module>
    from project import app
  File "/Users/pasquale/git/ted-talk-topic-extraction/app/project.py", line 16, in <module>
    api_doc(app, config_path='swagger.yml', url_prefix='/', title='Topic Model API')
  File "/usr/local/lib/python3.7/site-packages/swagger_ui/old.py", line 25, in __init__
    super(FlaskInterface, self).__init__(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/swagger_ui/core.py", line 33, in __init__
    getattr(self, '_{}_handler'.format(app_type))()
  File "/usr/local/lib/python3.7/site-packages/swagger_ui/core.py", line 142, in _flask_handler
    self._app.register_blueprint(swagger_blueprint)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 98, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1168, in register_blueprint
    blueprint.register(self, options, first_registration)
  File "/usr/local/lib/python3.7/site-packages/flask/blueprints.py", line 257, in register
    deferred(state)
  File "/usr/local/lib/python3.7/site-packages/flask/blueprints.py", line 295, in <lambda>
    self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))
  File "/usr/local/lib/python3.7/site-packages/flask/blueprints.py", line 87, in add_url_rule
    **options
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 98, in wrapper_func
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1275, in add_url_rule
    rule = self.url_rule_class(rule, methods=methods, **options)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/routing.py", line 666, in __init__
    raise ValueError("urls must start with a leading slash")
ValueError: urls must start with a leading slash

How to use this with AWS Lamda?

Assume i have an open api json/yaml spec, i want a lambda function to return the swagger ui as a response via api gateway

i.e.

User ---> API Gateway ---> AWS Lambda -->  Open API Spec (YAML / JSON) stored in lambda zip or in S3

and the user sees the swagger UI

How to set configuration values dynamically

Hi all,
I was wondering is, using this api, it would be possible to set some configuration value dynamically. It would be great thinking about the API version for example.
In this way we can leave the config file as it is but the version displayed would change automatically according to git tag name or environment variables

Not sure if this is a bug. CSS/js in production redirect to "base url"

I use swagger-ui-py==21.12.8 and locally Openapi documentation is created without problems and I can enjoy it at

http://localhost:8005/api/doc (8005 is custom).

We deploy in our preview envs, and this url works fine

https://preview-newe-2253-a9wd53-debug.preview.gfknewron.com/insight/additive-decomposition/api/doc/swagger.json

But htis one

https://preview-newe-2253-a9wd53-debug.preview.gfknewron.com/insight/additive-decomposition/api/doc/

has problems with resources

GET https://preview-newe-2253-a9wd53-debug.preview.gfknewron.com/api/doc/static/swagger-ui.css net::ERR_ABORTED 404

it should have been

https://preview-newe-2253-a9wd53-debug.preview.gfknewron.com/insight/additive-decomposition/api/doc/static/swagger-ui.css

The urls are generated from our deployment scripts.

Is there something I can do? Is this a misuse of the library on my part?

Any idea what is missing?

Python 3.10.3 on MacOS Big sur, x86-64, installed through pyenv. flask==2.1.0

Bug: doesn`t work well with falcon 3.0.1

when i use
api_doc(app, config_path='./swagger.json', url_prefix='/api/doc', title='API doc')
and visit /api/doc, got 404 error

Then i tried using falcon_api_doc instead, got these error and cannot start server:
Traceback (most recent call last):
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker
worker.init_process()
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/workers/base.py", line 134, in init_process
self.load_wsgi()
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi
self.wsgi = self.app.wsgi()
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi
self.callable = self.load()
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 58, in load
return self.load_wsgiapp()
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp
return util.import_app(self.app_uri)
File "/root/customerportal/env/lib64/python3.6/site-packages/gunicorn/util.py", line 359, in import_app
mod = importlib.import_module(module)
File "/usr/lib64/python3.6/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 665, in _load_unlocked
File "", line 678, in exec_module
File "", line 219, in call_with_frames_removed
File "/root/customerportal/app.py", line 25, in
falcon_api_doc(app, config_path='./swagger.json', url_prefix='/api/doc', title='API doc')
File "/root/customerportal/env/lib64/python3.6/site-packages/swagger_ui/old.py", line 37, in init
super(FalconInterface, self).init(*args, **kwargs)
File "/root/customerportal/env/lib64/python3.6/site-packages/swagger_ui/core.py", line 36, in init
getattr(self, '
{}_handler'.format(app_type))()
TypeError: _falcon_handler() missing 1 required positional argument: 'use_async'

falcon_api_doc returns unexpected arg error

error

line 31, in <module>
    falcon_api_doc(app, config_path=swagger_path,url_prefix='/api/doc')
line 24, in _api_doc
    return api_doc(app, **kwargs)
line 18, in api_doc
    return handler(doc)
line 30, in handler
    doc.app.add_route(doc.root_uri_absolute(slashes=True), 
line 352, in add_route
    self._router.add_route(uri_template, method_map, resource, *args,
TypeError: add_route() got an unexpected keyword argument 'suffix'

my code

app = falcon.API(
    middleware=[
        middleware.Auth('/api', configs.API_KEYS),
        Middleware()
    ]
)

db = sqlalchemy.create_engine(configs.DB_URL)

tables = models.build_tables(db)

api_routes = broutes.attach_routes(app, db)
static_routes = froutes.attach_routes(app)

from swagger_ui import falcon_api_doc
import os
working_dir = os.path.dirname(os.path.abspath(__file__))
swagger_path = os.path.join(working_dir, 'swagger.json')
falcon_api_doc(app, config_path=swagger_path,url_prefix='/api/doc')

httpd = simple_server.make_server("0.0.0.0", 80, app)
httpd.serve_forever()

falcon: 1.4.1
swagger-ui-py: 21.12.8

Any ideas on how to troubleshoot?

Serve api specification from web address, not from file

Especially for developing purposes and not following the spec first approach it would be nice if it wouldn't be necessary to write a file to disc before using swagger-ui-py. Serving from a web address is appreciated.
Thanks for your work so far.

[BUG] Servers section is broken, prevents usage of "Try it Out"

In my generated swagger.json, I see the correctly generated servers section:

"servers": [
        {
            "url": "http://localhost:80/",
            "description": "Local environment"
        },
        {
            "url": "http://foo.com",
            "description": "Main Endpoint"
        }
    ],

But in the swagger UI I see only one autogenerated server with a malformed URL with a comma:

https://somedomain.com/,somedomain.com

I'm guessing it's trying to do some kind of logic to support reverse proxies... but that logic seems broken. Do you know where the code lives for this?

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.