Today, I’m going to show you how to build a REST API application for a mobile application. My customer wants it to be serverless and run in AWS Lambda. Hmm, because Serverless is one modern buzz word besides many buzzwords right now. In fact, if you don’t want to care about managing infrastructure and scaling, a serverless service will help us to focus on building the application. AWS Lambda is one of those that let us run any WSGI application on the cloud.

To get started step-by-step, we will:

Prerequisites

Getting started

– You’ll need the Serverless Framework installed:

npm install -g serverless

– Configure AWS credentials:

– Visit this URL for a tutorial to set up AWS credentials.

$ aws configure --profile nano-api

AWS Access Key ID [None]: XXXXXXXXXXXXXXXXXXXX

AWS Secret Access Key [None]: XXXXXXXXXXXXXXXXXXXXXXX

Default region name [None]: us-east-1

Default output format [None]: text

Create an API application using Flask

Let’s build a Flask app first.

$ mkdir nano-api

$ cd nano-api

$ virtualenv -p python3 .venv

$ source .venv/bin/activate

$ (.venv) pip install Flask

$ (.venv) pip freeze > requirements.txt

After that, Create a file app.py:

# app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")

def hello():

    return "Hello TwentyCI!"

This is a very simple application that returns “Hello World!” when a request comes in on the root path /.

Deploy to AWS Lambda using Serverless

We’re going to use the serverless-wsgi plugin for negotiating the API Gateway event type into the WSGI format that Flask expects. We’ll also use the serverless-python-requirements plugin for handling our Python packages on deployment.

$ npm install --save-dev serverless-wsgi serverless-python-requirements

To get this application deployed, create a serverless.yml in the working directory:

# serverless.yml

service: serverless-flask

plugins:

- serverless-python-requirements

- serverless-wsgi

custom:

wsgi:

app: app.app

packRequirements: false

pythonRequirements:

dockerizePip: non-linux

provider:

name: aws

runtime: python3.7

stage: dev

region: us-east-1

functions:

app:

handler: wsgi.handler

events:

- http: ANY /

- http: 'ANY {proxy+}'

Now, deploy your function:

$ sls deploy

...

Service Information

service: serverless-flask

stage: dev

region: us-east-1

stack: serverless-flask-dev

api keys:

None

endpoints:

ANY - https://k1xz6ol912.execute-api.us-east-1.amazonaws.com/dev

ANY - https://k1xz6ol912.execute-api.us-east-1.amazonaws.com/dev/{proxy+}

functions:

app: serverless-flask-dev-app

And, follow your endpoints in the Service Information section, it works!

This is a very simple example, but the above process is very same for larger apps in the future.

Cuong Giang

Share with us your business goals and product ideas, we will support you to develop, scale and succeed together.