Skip to content

Commit 7091652

Browse files
committed
feat: Add aws-python-flask-dynamodb-api template
1 parent bf5a5ff commit 7091652

File tree

6 files changed

+319
-0
lines changed

6 files changed

+319
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ serverless install -u https://github.com/serverless/examples/tree/master/folder-
108108
| [Aws Alexa Skill](https://github.com/serverless/examples/tree/master/aws-python-alexa-skill) <br/> This example demonstrates how to use an AWS Lambdas for your custom Alexa skill. | python |
109109
| [Aws Auth0 Api Gateway](https://github.com/serverless/examples/tree/master/aws-python-auth0-custom-authorizers-api) <br/> Demonstration of protecting API gateway endpoints with auth0 | python |
110110
| [Aws Python Flask Api](https://github.com/serverless/examples/tree/master/aws-python-flask-api) <br/> Example of a Python Flask API service with traditional Serverless Framework | python |
111+
| [Aws Python Flask Dynamodb Api](https://github.com/serverless/examples/tree/master/aws-python-flask-dynamodb-api) <br/> Example of a Python Flask API service backed by DynamoDB with traditional Serverless Framework | python |
111112
| [Aws Python Line Echo Bot](https://github.com/serverless/examples/tree/master/aws-python-line-echo-bot) <br/> this is echo bot on LINE message | python |
112113
| [Aws Python Pynamodb S3 Sigurl](https://github.com/serverless/examples/tree/master/aws-python-pynamodb-s3-sigurl) <br/> Serverless signed uploader REST API using pynamodb, s3 generated events, custom log format, and DRY serverless.yml with custom section | python |
113114
| [Aws Rest With Dynamodb](https://github.com/serverless/examples/tree/master/aws-python-rest-api-with-dynamodb) <br/> Serverless CRUD service exposing a REST HTTP interface | python |
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
<!--
2+
title: 'Serverless Framework Python Flask API backed by DynamoDB on AWS'
3+
description: 'This template demonstrates how to develop and deploy a simple Python Flask API service backed by DynamoDB running on AWS Lambda using the traditional Serverless Framework.'
4+
layout: Doc
5+
framework: v2
6+
platform: AWS
7+
language: Python
8+
authorLink: 'https://github.com/serverless'
9+
authorName: 'Serverless, inc.'
10+
authorAvatar: 'https://avatars1.githubusercontent.com/u/13742415?s=200&v=4'
11+
-->
12+
13+
# Serverless Framework Python Flask API service backed by DynamoDB on AWS
14+
15+
This template demonstrates how to develop and deploy a simple Python Flask API service, backed by DynamoDB, running on AWS Lambda using the traditional Serverless Framework.
16+
17+
18+
## Anatomy of the template
19+
20+
This template configures a single function, `api`, which is responsible for handling all incoming requests thanks to configured `http` events. To learn more about `http` event configuration options, please refer to [http event docs](https://www.serverless.com/framework/docs/providers/aws/events/apigateway/). As the events are configured in a way to accept all incoming requests, `Flask` framework is responsible for routing and handling requests internally. The implementation takes advantage of `serverless-wsgi`, which allows you to wrap WSGI applications such as Flask apps. To learn more about `serverless-wsgi`, please refer to corresponding [GitHub repository](https://github.com/logandk/serverless-wsgi). The template also relies on `serverless-python-requirements` plugin for packaging dependencies from `requirements.txt` file. For more details about `serverless-python-requirements` configuration, please refer to corresponding [GitHub repository](https://github.com/UnitedIncome/serverless-python-requirements).
21+
22+
Additionally, the template also handles provisioning of a DynamoDB database that is used for storing data about users. The Flask application exposes two endpoints, `POST /users` and `GET /user/{userId}`, which allow to create and retrieve users.
23+
24+
## Usage
25+
26+
### Prerequisites
27+
28+
In order to package your dependencies locally with `serverless-python-requirements`, you need to have `Python3.8` installed locally. You can create and activate a dedicated virtual environment with the following command:
29+
30+
```bash
31+
python3.8 -m venv ./venv
32+
source ./venv/bin/activate
33+
```
34+
35+
Alternatively, you can also use `dockerizePip` configuration from `serverless-python-requirements`. For details on that, please refer to corresponding [GitHub repository](https://github.com/UnitedIncome/serverless-python-requirements).
36+
37+
### Deployment
38+
39+
This example is made to work with the Serverless Framework dashboard, which includes advanced features such as CI/CD, monitoring, metrics, etc.
40+
41+
In order to deploy with dashboard, you need to first login with:
42+
43+
```
44+
serverless login
45+
```
46+
47+
install dependencies with:
48+
49+
```
50+
npm install
51+
```
52+
53+
and then perform deployment with:
54+
55+
```
56+
serverless deploy
57+
```
58+
59+
After running deploy, you should see output similar to:
60+
61+
```bash
62+
Serverless: Using Python specified in "runtime": python3.8
63+
Serverless: Packaging Python WSGI handler...
64+
Serverless: Generated requirements from /home/xxx/xxx/xxx/examples/aws-python-flask-dynamodb-api/requirements.txt in /home/xxx/xxx/xxx/examples/aws-python-flask-dynamodb-api/.serverless/requirements.txt...
65+
Serverless: Using static cache of requirements found at /home/xxx/.cache/serverless-python-requirements/62f10436f9a1bb8040df30ef2db5736c8015b18256bf0b6f1b0cbb2640030244_slspyc ...
66+
Serverless: Packaging service...
67+
Serverless: Excluding development dependencies...
68+
Serverless: Injecting required Python packages to package...
69+
Serverless: Creating Stack...
70+
Serverless: Checking Stack create progress...
71+
........
72+
Serverless: Stack create finished...
73+
Serverless: Uploading CloudFormation file to S3...
74+
Serverless: Uploading artifacts...
75+
Serverless: Uploading service aws-python-flask-dynamodb-api.zip file to S3 (1.3 MB)...
76+
Serverless: Validating template...
77+
Serverless: Updating Stack...
78+
Serverless: Checking Stack update progress...
79+
.................................
80+
Serverless: Stack update finished...
81+
Service Information
82+
service: aws-python-flask-dynamodb-api
83+
stage: dev
84+
region: us-east-1
85+
stack: aws-python-flask-dynamodb-api-dev
86+
resources: 12
87+
api keys:
88+
None
89+
endpoints:
90+
ANY - https://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/
91+
ANY - https://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/{proxy+}
92+
functions:
93+
api: aws-python-flask-dynamodb-api-dev-api
94+
layers:
95+
None
96+
```
97+
98+
_Note_: In current form, after deployment, your API is public and can be invoked by anyone. For production deployments, you might want to configure an authorizer. For details on how to do that, refer to [http event docs](https://www.serverless.com/framework/docs/providers/aws/events/apigateway/).
99+
100+
### Invocation
101+
102+
After successful deployment, you can create a new user by calling the corresponding endpoint:
103+
104+
```bash
105+
curl --request POST 'https://xxxxxx.execute-api.us-east-1.amazonaws.com/dev/users' --header 'Content-Type: application/json' --data-raw '{"name": "John", "userId": "someUserId"}'
106+
```
107+
108+
Which should result in the following response:
109+
110+
```bash
111+
{"userId":"someUserId","name":"John"}
112+
```
113+
114+
You can later retrieve the user by `userId` by calling the following endpoint:
115+
116+
```bash
117+
curl https://xxxxxxx.execute-api.us-east-1.amazonaws.com/dev/users/someUserId
118+
```
119+
120+
Which should result in the following response:
121+
122+
```bash
123+
{"userId":"someUserId","name":"John"}
124+
```
125+
126+
If you try to retrieve user that does not exist, you should receive the following response:
127+
128+
```bash
129+
{"error":"Could not find user with provided \"userId\""}
130+
```
131+
132+
### Local development
133+
134+
Thanks to capabilities of `serverless-wsgi`, it is also possible to run your application locally, however, in order to do that, you will need to first install `werkzeug`, `boto3` dependencies, as well as all other dependencies listed in `requirements.txt`. It is recommended to use a dedicated virtual environment for that purpose. You can install all needed dependencies with the following commands:
135+
136+
```bash
137+
pip install werkzeug boto3
138+
pip install -r requirements.txt
139+
```
140+
141+
Additionally, you will need to emulate DynamoDB locally, which can be done by using `serverless-dynamodb-local` plugin. In order to do that, execute the following commands:
142+
143+
```bash
144+
serverless plugin install -n serverless-dynamodb-local
145+
serverless dynamodb install
146+
```
147+
148+
It will add the plugin to `devDependencies` in `package.json` file as well as to `plugins` section in `serverless.yml`. Additionally, it will also install DynamoDB locally.
149+
150+
You should also add the following config to `custom` section in `serverless.yml`:
151+
152+
153+
```yml
154+
custom:
155+
(...)
156+
dynamodb:
157+
start:
158+
migrate: true
159+
stages:
160+
- dev
161+
```
162+
163+
Additionally, we need to reconfigure DynamoDB Client to connect to our local instance of DynamoDB. We can take advantage of `IS_OFFLINE` environment variable set by `serverless-wsgi` plugin and replace:
164+
165+
166+
```python
167+
dynamodb_client = boto3.client('dynamodb')
168+
```
169+
170+
with
171+
172+
```python
173+
dynamodb_client = boto3.client('dynamodb')
174+
175+
if os.environ.get('IS_OFFLINE'):
176+
dynamodb_client = boto3.client('dynamodb', region_name='localhost', endpoint_url='http://localhost:8000')
177+
```
178+
179+
Now you can start DynamoDB local with the following command:
180+
181+
```bash
182+
serverless dynamodb start
183+
```
184+
185+
At this point, you can run your application locally with the following command:
186+
187+
```bash
188+
serverless wsgi serve
189+
```
190+
191+
For additional local development capabilities of `serverless-wsgi` and `serverless-dynamodb-local` plugins, please refer to corresponding GitHub repositories:
192+
- https://github.com/logandk/serverless-wsgi
193+
- https://github.com/99x/serverless-dynamodb-local

aws-python-flask-dynamodb-api/app.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import os
2+
3+
import boto3
4+
from flask import Flask, jsonify, make_response, request
5+
6+
app = Flask(__name__)
7+
8+
9+
dynamodb_client = boto3.client('dynamodb')
10+
11+
if os.environ.get('IS_OFFLINE'):
12+
dynamodb_client = boto3.client(
13+
'dynamodb', region_name='localhost', endpoint_url='http://localhost:8000'
14+
)
15+
16+
17+
USERS_TABLE = os.environ['USERS_TABLE']
18+
19+
20+
@app.route('/users/<string:user_id>')
21+
def get_user(user_id):
22+
result = dynamodb_client.get_item(
23+
TableName=USERS_TABLE, Key={'userId': {'S': user_id}}
24+
)
25+
item = result.get('Item')
26+
if not item:
27+
return jsonify({'error': 'Could not find user with provided "userId"'}), 404
28+
29+
return jsonify(
30+
{'userId': item.get('userId').get('S'), 'name': item.get('name').get('S')}
31+
)
32+
33+
34+
@app.route('/users', methods=['POST'])
35+
def create_user():
36+
user_id = request.json.get('userId')
37+
name = request.json.get('name')
38+
if not user_id or not name:
39+
return jsonify({'error': 'Please provide both "userId" and "name"'}), 400
40+
41+
dynamodb_client.put_item(
42+
TableName=USERS_TABLE, Item={'userId': {'S': user_id}, 'name': {'S': name}}
43+
)
44+
45+
return jsonify({'userId': user_id, 'name': name})
46+
47+
48+
@app.errorhandler(404)
49+
def resource_not_found(e):
50+
return make_response(jsonify(error='Not found!'), 404)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"name": "aws-python-flask-dynamodb-api",
3+
"version": "1.0.0",
4+
"description": "Example of a Python Flask API service backed by DynamoDB with traditional Serverless Framework",
5+
"author": "",
6+
"devDependencies": {
7+
"serverless-python-requirements": "^5.1.0",
8+
"serverless-wsgi": "^1.7.6"
9+
}
10+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Flask==1.1.2
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
service: aws-python-flask-dynamodb-api
2+
3+
frameworkVersion: '2'
4+
variablesResolutionMode: '20210219'
5+
configValidationMode: 'error'
6+
7+
custom:
8+
tableName: 'users-table-${self:provider.stage}'
9+
wsgi:
10+
app: app.app
11+
12+
provider:
13+
name: aws
14+
runtime: python3.8
15+
lambdaHashingVersion: '20201221'
16+
stage: dev
17+
iam:
18+
role:
19+
statements:
20+
- Effect: Allow
21+
Action:
22+
- dynamodb:Query
23+
- dynamodb:Scan
24+
- dynamodb:GetItem
25+
- dynamodb:PutItem
26+
- dynamodb:UpdateItem
27+
- dynamodb:DeleteItem
28+
Resource:
29+
- Fn::GetAtt: [ UsersTable, Arn ]
30+
apiGateway:
31+
shouldStartNameWithService: true
32+
environment:
33+
USERS_TABLE: ${self:custom.tableName}
34+
35+
functions:
36+
api:
37+
handler: wsgi_handler.handler
38+
events:
39+
- http:
40+
path: /
41+
method: ANY
42+
- http:
43+
path: /{proxy+}
44+
method: ANY
45+
46+
plugins:
47+
- serverless-wsgi
48+
- serverless-python-requirements
49+
50+
resources:
51+
Resources:
52+
UsersTable:
53+
Type: AWS::DynamoDB::Table
54+
Properties:
55+
AttributeDefinitions:
56+
- AttributeName: userId
57+
AttributeType: S
58+
KeySchema:
59+
- AttributeName: userId
60+
KeyType: HASH
61+
ProvisionedThroughput:
62+
ReadCapacityUnits: 1
63+
WriteCapacityUnits: 1
64+
TableName: ${self:custom.tableName}

0 commit comments

Comments
 (0)