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) –> private key for my domain
2) –>Self signed certificate

openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout -out

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/')
key = os.path.join(os.path.dirname(__file__), 'resources/')

app = Flask(__name__)

def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    context = (cer, key) host='', 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 (Press CTRL+C to quit)
* Restarting with stat
  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

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s