Search code examples
flaskswaggertokenbasic-authenticationflasgger

how to load swagger UI, in before_request looking for token but token used in particular endpoint


#flask, swagger, before_request problem in app.py one function is decorated with before_request and in this fuction """ token = request.args.get('token') if not token: return jsonify({ 'status': 'error', 'message': 'Unauthorized.' })

    # Parse Token
    token = base64.urlsafe_b64decode(token)
    token = token.decode('utf-8')"""

suppose i have some endpoints like /api/employees when i want load swagger UI its unauthrize becauz of before request. so i want to load ui, and afterthat in parameter token send to get response from endpoints if you have simliar scenerio please share me support doc


Solution

  • In this case we have to bypass some URLs like '/apidocs', '/', and some HTML, css, jquery related config have to add in swagger config.

    @app.before_request
    def before_request():
    
        if request.path == '/apidocs' or request.path == '/apispec.json':
            return shutdown_session() 
        try:
           # some code here
        except:
           # something here
    

    in swagger config you have add like this

    swagger_config = {
        "headers": [
        ],
        "specs": [
            {
                "endpoint": 'apispec',
                "route": '/apispec.json',
                "rule_filter": lambda rule: True,  # all in
                "model_filter": lambda tag: True,  # all in
            }
        ],
    
        "static_url_path": "/flasgger_static",
        "swagger_ui": True,
        "specs_route": "/apidocs",
        'swagger_ui_bundle_js':  '//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js',
        'swagger_ui_standalone_preset_js': '//unpkg.com/swagger-ui-dist@3/swagger-ui-standalone-preset.js',
        'jquery_js': '//unpkg.com/[email protected]/dist/jquery.min.js',
        'swagger_ui_css': '//unpkg.com/swagger-ui-dist@3/swagger-ui.css'
    }