Python Flask API in HTTPS

Posted: October 21, 2015 in Uncategorized
Tags: , , , ,

Before starting a server with SSL, you need to create private key and a certificate. I will create a self signed certificate for this tutorial.
Below commands will ask for information regarding your certirficate. Among them, ‘common name’ is the most important inforamtion. It should be the domain name of your server running. This will output two files,

1) udara.com.key –> private key for my domain
2) udara.com.ct –>Self signed certificate

openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout udara.com.key -out udara.com.crt

Below is the Flask code snippet to start your Flask API in HTTPS

from flask import Flask
from OpenSSL import SSL

import os

context = SSL.Context(SSL.SSLv23_METHOD)
cer = os.path.join(os.path.dirname(__file__), 'resources/udara.com.crt')
key = os.path.join(os.path.dirname(__file__), 'resources/udara.com.key')

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    context = (cer, key)
    app.run( host='0.0.0.0', port=5000, debug = True, ssl_context=context)

When you run above code, it will show below output. Note that it is running HTTPS

* Running on https://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
Advertisements
Comments
  1. sukumaar says:

    It is working but chrome and firefox is showing security worning

    • Yes, browsers should show a warning because they don’t trust the certificated you created. Either add your certificate as a trusted one or use a Certificate Authority signed certificate instead of a self singed certificate.
      Please refer to [1] for more details
      [1]https://support.mozilla.org/en-US/kb/connection-untrusted-error-message#w_certificates-and-identification

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s