Creating Serverless Python API


INTRODUCTION

This article we are going to discuss about Creating Serverless Python API. We are going to separate this article into three big part. First part, we are going to build an api using Chalice & Lambda. Second part , we are going to build an api using Zappa & Lambda and third part , we going to use Serverless & AWS.

I. Chalice & Lambda

1. AWS Setup

  • First of all , we need to install awscli to configure our aws credential.
pip install awscli
  • Configure
aws configure

AWS Access Key ID [None]: input your access key
AWS Secret Access Key [None]: input your secret access key
Default region name [None]: input your region
Default output format [None]: json
  • Verifies
aws s3 ls

2. Chalice

Now it's time for us to play with chalice , first let us install chalice.

  • Install chalice
pip install chalice
  • Create Chalcie project
chalice new-project chalice_project_name
cd chalice_project_name
ls

You will see two files which are.
1.chalice_project_name.py : It is a default chalice app.
2.requirements : just a blank text

you can open the chalice_project_name.py file to see what is going on.after that let us deploy.

  • Deploy
chalice deploy

it will take a while and you will seee something like this

Creating role: chalice_project_name-dev
Creating deployment package.
Creating lambda function: chalice_project_name-dev
Initiating first time deployment.
Deploying to API Gateway stage: api
https://a23wxp5cve.execute-api.eu-west-1.amazonaws.com/api/

copy that URL and paste it in the browser, you will see the response of your api. Now you can modify the API to follow what you need.

3. Chalice Undeploy

after you are done playing around with chalice , you can undeploy it by doing like so.

chalice undeploy --stage-dev

II. Zappa & Lambda

Zappa is a wonderful python package created by Miserlou.It saved us a lot of time and allows users to deploy code to Lambda with minimal configuration with just one command from the CLI.
Thing to note : Zappa only work in virtual environment.

1.Setting Up

Now let start install virtual env.

  • Installing virtual env
pip install pipenv
  • Setting up virtual env
pipenv --three
pipenv shell
  • Now verifies you are connected to aws
aws s3 ls
  • Ok now let install zappa and flask
pipenv install zappa flask

2.Build API

Ok, we have finished the setup. Now let us use flask to build the sample api.

from flask import Flask , jsonify
app = Flask(__name__)

@app.route("/quad")
def hello():
    return jsonify({"result":"success"})

if __name__ == '__main__':
    app.run(debug=True)
  • You can run the app.py and see the response on the localhost and now it time to deploy it with zappa.

3.Zappa Deploy

zappa init

this will create your zappa_settings.json file and add it to the project, now you can deploy! This is what makes zappa so nice, it takes this tiny config and then packages and deploys with one command. Ok now let deploy zappa.

zappa deploy

This will give you something like this.

copy the link and paste it in the browser, you will see the response of the API.

4.Zappa Undeploy

If you are follow this tutorial just for testing purpose , after play around with it. You can delete it by below command :

zappa undeploy

III. Serverless & AWS

This time we going to use python flask to build a sample API and use serverless to deploy it into AWS.

1.Setting Up

  • first, let us create our working directories.
mkdir APIwithServerless
cd APIwithServerless
  • ok now let's install the serverless python plug in.
npm install --save serverless-wsgi
  • then let's build serverless.
serverless create --template aws-python3

there are many template, you can use serverless create --template --help to see. Since I am using python3.6 so I'm going with above template and after run the command you will get two file in the directories.
1. serverless.yml
2. handler

  • Ok , now last thing we need to do is : we need to create an requirements.txt because we are using serverless-plugin and it will looking for that file to install needed library.
mkdir requirements.txt
  • Since we need flask to run the app , now let add Flask to the requirements.txt
echo "Flask==0.12.2" >> requirements.txt

yes , that it we are done with set up.

2.Build API

Now it time to build our API. create an .py file and name it createAPI

#File name = "createAPI"

from flask import Flask , jsonify
app = Flask(__name__)

@app.route("/")
def response():
    return jsonify({"result":"success"})

if __name__ == '__main__':
    app.run(debug=True)
  • now try running the file in our local computer by:
export FLASK_APP=createAPI.py
flask run
  • now you should see the response in your localhost. let deploy it into aws :).

3.API deploy With Serverless

before we deploy our api we need to configure our serverless.yml file.

  • open the file
open serverless.yml
  • Delete default configure and write this

service: aws-python3 # NOTE: update this with your service name

provider:
  name: aws
  runtime: python3.6

plugins:
  - serverless-wsgi

functions:
  createAPI:
    handler: wsgi.handler
    events:
      - http: ANY {proxy+}
      - http: ANY /

custom:
  wsgi:
    app: createAPI.app
  • now save the and we finally can deploy it.
sls deploy

it will take a while and you will see this.

  • copy url in the endpoins and paste it in your web browser. You will the our API response :)

4.Serverless Undeploy

If you are done playing with it and you want to undeploy the project. You can do it like so.

sls remove