In [44]:
from IPython.display import Image
Image(filename='viralml-book.png', width=600)
Out[44]:

Starting a Business?

Learn about REST APIs and Flask - these are great building block for a SaaS or data-provider business

If you are looking to start a business or a side-hustle, this is an easy and simple place to start - Join me this Sunday for a live YouTube

A Quote Dispensing REST API Function

Here are some great from the classic book "The Little Prince" by Antoine de Saint-Exupéry (https://amzn.to/2MzcWLt). Our REST API function will simply return a random quote from our data frame whenever asked.

In [45]:
quotes = '''
"And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye."
"All grown-ups were once children... but only few of them remember it."
"What makes the desert beautiful,' said the little prince, 'is that somewhere it hides a well..."
"It is the time you have wasted for your rose that makes your rose so important."
"The most beautiful things in the world cannot be seen or touched, they are felt with the heart."
"You become responsible forever for what you’ve tamed."
'''
quotes
Out[45]:
'\n"And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye."\n"All grown-ups were once children... but only few of them remember it."\n"What makes the desert beautiful,\' said the little prince, \'is that somewhere it hides a well..."\n"It is the time you have wasted for your rose that makes your rose so important."\n"The most beautiful things in the world cannot be seen or touched, they are felt with the heart."\n"You become responsible forever for what you’ve tamed."\n'
In [46]:
quotes_df = pd.read_csv('quotes.csv', header=None, names = ['Quote'])
list(quotes_df['Quote'].sample())[0]
Out[46]:
'All grown-ups were once children... but only few of them remember it.'

New Account on DigitalOcean

First step is to sign up for an account on Digital Ocean. It offers a "$50, 30-day free trial requires valid credit card"

In [47]:
Image(filename='digitalocean-signup-deal.png', width=600)
Out[47]:

You may be asked to choose a platform, keep it simple and go with Python:

In [48]:
Image(filename='digital-ocean-platform.png', width=600)
Out[48]:
In [49]:
Image(filename='create-droplet.png', width=600)
Out[49]:

Go with the chepeast options - a good one is Ubuntu and the smallest slice available currently at $5/mo (remember it is free as you have $50 credit - just remember to turn things off when you are done).

In [50]:
Image(filename='do-cheapest-options.png', width=600)
Out[50]:

Go with all the defaults and let's start coding!

Keeping it simple and coding directly from the dashboard

You will get an email once your droplet is created. Click on the droplet's address in your dashboard

In [51]:
Image(filename='click-on-droplet-to-start.png', width=600)
Out[51]:

Open the console for your droplet and let's get to work.

In [52]:
Image(filename='do-open-console.png', width=600)
Out[52]:

This will open a new browser window with the look-and-feel of a terminal window. It will ask for a login and password. The login is 'root' and the passowrd was emailed to you when you created the droplet. Go ahead and log in. It will also ask that you set up a new password.

(I am using the guide: https://pythonforundergradengineers.com/flask-app-on-digital-ocean.html)

In your console window, run the following packages:

sudo apt-get update -y
sudo apt-get upgrade -y
sudo apt-get install python3-pip -y
sudo apt-get install python3-dev -y 
sudo apt-get install python3-setuptools -y
sudo apt-get install build-essential libssl-dev libffi-dev -y

Make our 'flaskapp' directory:

cd ~
mkdir flaskapp
cd flaskapp
apt-get install python3-venv
python3.6 -m venv flaskappenv
source flaskappenv/bin/activate

We are now in the virtual environment with Python 3.6 enabled (change any of these steps/versions when new versions require it).

Install the following in our virtual environment:

pip install wheel
pip install flask
pip install uwsgi
pip install pandas
pip3 install flask-restful

Use "vi" to paste the quotes in a file called quotes.csv. This can be done by using the command:

vi quotes.csv

Next, hit the 'i' key to get into 'insert' mode. Paste each line one at a time to make sure they are newline delimited (we'll see a better way of doing in another session). Once you are done, the command to exit 'vi' is 'ESC', ':', 'wq', if you want to leave without saving the file, 'ESC', ':', 'q!'

Let's create our Flask Appliction

Open 'vi' again using the command:

 vi flaskapp.py

And hit the 'i' key to get into insert mode and paste the following code:

In [ ]:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def index():
    return "Hello from ViralML!!!"

if __name__ == "__main__":
    app.run(host='0.0.0.0')
    

To run our web application, run the following two commands:

sudo ufw allow 5000
python flaskapp.py

Find out what is your IP address for your droplet and append ":5000" to the end of it. In my case it is:

http://159.65.218.240:5000/
In [53]:
Image(filename='droplet-ip-address.png', width=600)
Out[53]:
In [54]:
Image(filename='flask-app-is-live.png', width=600)
Out[54]:

We're good to go and have our live presence on the web!! This isn't the way you would run a production server but it is close and we'll look at the real deal in another session.

REST API

We are now ready to transform this simple flask application into a Restful API, quote yielding machine!

Hit 'CTRL-c' to kill the flask web server and open up the 'flaskapp.py' file using the command:

vi flaskapp.py

Update the existing code with the following code using the 'i' command to get into insert mode. When you are done, run the 'wq' command to save the changes:

In [ ]:
from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
  def get(self):
    return {'viralml': 'Hello World!'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
  app.run(debug=True)

Now let's change things around one more time by adding our quote sampling code:

In [ ]:
from flask import Flask, request
from flask_restful import Resource, Api
import pandas as pd

app = Flask(__name__)
api = Api(app)

# load data into memory
quotes_df = pd.read_csv('quotes.csv', header=None, names = ['Quote'])

class GetQuote(Resource):
  def get(self):
    global quotes_df
    newquote = list(quotes_df['Quote'].sample())[0]
    return {'Quote': newquote}
  

api.add_resource(GetQuote)

if __name__ == '__main__':
  app.run(debug=True)
In [55]:
Image(filename='quote-sampler.png', width=600)
Out[55]:

Remember!!

Remember to turn things off when you are done as the clock is ticking and you will be charged once your credits are gone.

If you are done - destroy the instance:

In [17]:
Image(filename='do-destroy.png', width=600)
Out[17]: