|
| 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 |
0 commit comments