Create REST API with Pyhton (Flask) and Dockerize your Python




Hola amigos,

Today we are going to implement a rest API using Python and we will use swagger to document it!

What a nice day ;)

TL;DR

As usual, you may access source code in github :

https://github.com/NurettinYAKIT/nurettinyakit.com/tree/master/be-stock-python


Let's start. Step by step...

1. Create the python program

We are going to use

  • Flask
  • request
  • jsonify
  • iexfinance.stocks

So we need to import them 

from flask import Flask, request, jsonify
from iexfinance.stocks import Stock

Now  we may define our program as a flask app 

app = Flask(__name__)

Next step is creating a REST API

@app.route("/python/stock", methods=['POST'])
def stock_logic():

the Rest is easy, just call another api 

ticker = request.get_json()['symbol']

try:
stock = Stock(ticker.encode("utf-8"))
price = stock.get_price()
except Exception as e :
print("This is an error message! " + str(e) )

Here is the whole program 

from flask import Flask, request, jsonify
from iexfinance.stocks import Stock

app = Flask(__name__)

@app.route("/python/stock", methods=['POST'])
def stock_logic():
ticker = request.get_json()['symbol']

try:
stock = Stock(ticker.encode("utf-8"))
price = stock.get_price()
except Exception as e :
print("This is an error message! " + str(e) )

return jsonify(
ticker=ticker,
price=price
)

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

And tada! Now you have your application

Just run it!


2. Run it on docker

Create your Dockerfile

FROM python:2-alpine

ADD stock_logic.py /

RUN pip install --upgrade pip && \
pip install pip-tools && \
pip install -U setuptools

RUN apk add --update curl gcc g++ && \
ln -s /usr/include/locale.h /usr/include/xlocale.h

RUN pip install Flask
RUN pip install requests
RUN pip install jsonify
RUN pip install pandas
RUN pip install iexfinance

CMD [ "python", "./stock_logic.py" ]

EXPOSE 5000

Build the image

docker build -t be-stock-python .

run it!

docker run -i -t -p 5000:5000 be-stock-python

Bravo! Now your app is running on Docker ;)

Do you want to try? Just run a curl command 

curl --header "Content-Type: application/json" \
--request POST \
--data '{ "symbol":"GOOGL" }' \
http://localhost:5000/python/stock


Comments