RestAPI using Flask and AWS DynamoDB and deploying the image to Docker Hub

JANHAVI CHAURASIA
3 min readFeb 17, 2019

In this article I will show you how to built a RestAPI using flask and using AWS DynamoDB to fetch the data, and finally deploying the creating and deploying the image to Docker Hub.

Flask And RestAPI

Create a new file named requirements.txt and copy below the text in it.

boto3
Flask
awscli
datetime
simplejson

We would need to install them to make our application work. Boto is the Amazon Web Services (AWS) SDK for Python which would help us in connecting o AWS DynamoDB. Execute the bellow commend in terminal

pip install -r requirements.txt

Next we need to write python code.

import boto3
from flask import Flask,request,jsonify
from datetime import datetime
import simplejson as json
app = Flask(__name__)
@app.route('/', methods =['GET'])
def predict():
try:
re=request.args.get('id') ; try:
dynamo=boto3.resource('dynamodb')
t=dynamo.Table('table_name')
except:
raise Exception("Aws variables not set properly!!!")
try:
re=int(re);
except:
raise Exception("Please Specify the id")
try:
m=t.get_item( #fetching the items from the table with a certain id
Key={
'Customer_ID' : re
})
except:
raise Exception("No such table"); except Exception as a:
return jsonify({"error":str(a)})
else:
m=m['Item'];
js = json.dumps(m)
return js;
if __name__ == '__main__':
app.run(host='0.0.0.0',port=4000)

(Note: I have used Try in several part of the code so that error detection could be easy and more easily understandable.)

Now in terminal type

python app.py

Now open a brower, and type localhost:4000/?id=1

It would show Aws variables not set properly!!! even though we have specified the id.

We need to give access to the AWS DynamoDB and then only the script would be able to access it.

For this we will use awscli. First step is to create an IAM and giving it permission to DynamoDB. Also make note of the AWS Access Key ID and AWS Secret Access Key.

Now go to the cmd and search for aws.cmd file that was downloaded when we install awscli in requirements. Mine was in ~\AppData\Roaming\Python\Python36\Scripts.

aws configure

It will ask you to enter the AWS Access Key ID and AWS Secret Access Key and region and output format. Enter these information. Make sure the region entered is right.You can use https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region for help.

Now you are ready to go. Again run the application and test it on browser or using postman.

If everything went well… we can proceed to the next section.

Docker Image and Docker Hub

Hope you had already installed Docker. If not you can go to the official site to install it.

first we need to create a docker file.Create a file and name it Dockerfile.

FROM python:2.7-slim
WORKDIR /app
COPY . /app
# to install the requirements
RUN pip install --trusted-host pypi.python.org -r requirements.txt
EXPOSE 80
CMD ["python", "app.py"]

Put the above code in Dockerfile. Put the app.py ,requirements.txt ad Dockerfile in a same folder. Also make changes in app.py

app.run(host='0.0.0.0',port=80)

Now open Docker. Go to the location of the folder and

docker build --tag=myapi .

You can check the image formed by typing

docker image ls

Run a container

$ docker run -p 4000:80 --name s1 myapi

Now go to brower and type the url with port 4000 and with the id value. To know the ip

$ docker-machine ip

We will again see the same message.. Aws variables not set properly!!!

The problem is same that we encountered previously….

$ docker exec -i -t s1 /bin/bash

The above code will run our container in interactive mode.

cd
find / -name "aws.cmd"

Copy the path displayed and go to hat same folder and redo the steps.

Now exit the container. Re-run it.Now it would work.

But we still need to commit the changes done in the container to the original image. For this

$ docker commit s1 myapi

But we would need to re-do this step manually, every time we upload a new image. So we could automate this step by making some changes in our docker file.

RUN cd /usr/local/bin
RUN aws configure set aws_access_key_id <Your_id>
RUN aws configure set aws_secret_access_key <Your_key>
RUN aws configure set default.region <region_name>

Add the above in Dockerfile and re build the image.

Now to upload this image make an account in dockerhub.

Now login

$ docker login
$ docker tag myapi <username>/<repositoryname>

Fill in the repository and username. Now just Push

$ docker push <username>/<repositoryname>

--

--