Search code examples
python-3.xflaskflask-restplus

Serving Flask-RESTPlus on https server


I am relatively new to python and I created a micro service using flask-resplus. Works fine on my computer and on the dev server served with http. I dont have control on where the microservice could be deployed. In these case it seems is behind a load balancer(not sure of details), served with https.

The actual errors given by the browser: Can't read from server. It may not have the appropriate access-control-origin settings.

When i check the network developer tools i see it fails loading swagger.json. But is checking it using: http://hostname/api/swagger.json, instead of https.

I have been googling, and i ran into discussions of this issue. And this seemed to be the fix that could work without me having to change the library or configurations on the server.

However still i couldnt get it to work.

This is what i have:

on the api file:

api_blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(api_blueprint, doc='/doc/', version='1.0', title='My api',
          description="My api")

on the main app file:

from flask import Flask
from werkzeug.contrib.fixers import ProxyFix

from lib.api import api_blueprint

app = Flask(__name__)

app.wsgi_app = ProxyFix(app.wsgi_app)
app.register_blueprint(api_blueprint)

Also tried adding:

app.config['SERVER_URL'] = 'http://testfsdf.co.za' # but it dont look like is being considered

Using flask-restplus==0.9.2,

Any solution will be appreciated, as long as i dont need to make configurations on the container where the service will be deployed (am ok with setting environment variables), i.e. service need to be self contained. And if there is a version of flask-resplus that i can install with pip, that already has a fix i can appreciate.

Thanks a lot guys,


Solution

  • Overide API class with _scheme='https' option in spec property.

    class MyApi(Api):
        @property
        def specs_url(self):
            """Monkey patch for HTTPS"""
            scheme = 'http' if '5000' in self.base_url else 'https'
            return url_for(self.endpoint('specs'), _external=True, _scheme=scheme)
    
    api = MyApi(api_blueprint, doc='/doc/', version='1.0', title='My api',
            description="My api")