Serving Flask-RESTPlus on https server Serving Flask-RESTPlus on https server flask flask

Serving Flask-RESTPlus on https server


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")


The solution above works like a charm. There are couple of things you should check.

  1. Before applying the fix, make sure in your chrome developertools -> Network tab that whenever you reload the page(in https server) that shows the swagger UI, you get a mixed content error for swagger.json request.

  2. The solution in the above post solves the issue when deployed on an https server but locally it might give issue. For that you can use the environment variable trick.

  3. Set a custom environment variable or any variable which is already there on your https server while deploying your app. Check for the existence of that environment variable before applying the solution to make sure your app in running in the https server.

Now when you run the app locally, this hack won't be applied and swagger.json would be served through http and in your server it would be served via https. Implementation might look similar to this.

import osfrom flask import url_forfrom flask_restplus import Apiapp = Flask( __name__)if os.environ.get('CUSTOM_ENV_VAR'):    @property    def specs_url(self):        return url_for(self.endpoint('specs'), _external=True, _scheme='https')    Api.specs_url = specs_urlapi = Api(app)