|
| 1 | +## Serverless FastAPI with AWS Lambda |
| 2 | + |
| 3 | +Mangum allows us to wrap the API with a handler that we will package and deploy as a Lambda function in AWS. |
| 4 | +Then using AWS API Gateway we will route all incoming requests to invoke the lambda and handle the routing internally within our application. |
| 5 | + |
| 6 | +### Install Mangum |
| 7 | + |
| 8 | +```shell |
| 9 | +pip install mangum |
| 10 | +``` |
| 11 | + |
| 12 | +### Setup AWS Resources |
| 13 | +This tutorial should fall under the AWS free-tier to create, however continued usage of these resources will have associated costs. |
| 14 | + |
| 15 | +### Create S3 Bucket |
| 16 | +* Navigate to S3 in the AWS console and click Create Bucket. |
| 17 | +* Give it a name and click Create. In this example we're going to call it serverless-fastapi-lambda-dev |
| 18 | + |
| 19 | +### Upload Zip File |
| 20 | +Before we can create the lambda we need to package up our existing FastApi app so it's ready for AWS Lambda. |
| 21 | + |
| 22 | +The lambda won't be running in the virtual environment and will only be running one command (which we will determine when we create it) which will be **main.handler** So we need to install all the dependencies within the zip file since it won't be running pip install like we did locally. |
| 23 | + |
| 24 | +### Package Lambda |
| 25 | +Inside your terminal from the root directory of your project, CD into the Python Site Packages folder. |
| 26 | + |
| 27 | +```shell |
| 28 | +cd env/lib/python3.7/site-packages |
| 29 | +``` |
| 30 | + |
| 31 | +Then zip up the contents into the root of the project. |
| 32 | + |
| 33 | +```shell |
| 34 | +cd env/lib/python3.7/site-packages |
| 35 | +``` |
| 36 | + |
| 37 | +```shell |
| 38 | +zip -r9 path/to/root/of/project/function.zip |
| 39 | +``` |
| 40 | + |
| 41 | +CD back into the root of the project. |
| 42 | + |
| 43 | +```shell |
| 44 | +cd path/to/root/of/project |
| 45 | +``` |
| 46 | + |
| 47 | +Next we need to add the contents of the app folder so let's add that into the zip file. |
| 48 | + |
| 49 | +```shell |
| 50 | +zip -g ./function.zip -r app |
| 51 | +``` |
| 52 | + |
| 53 | +### Upload Zip File to S3 |
| 54 | +* Go inside the S3 bucket you just created and click Upload. |
| 55 | +* Add your zip file through the interface that pops up and and click Upload. |
| 56 | + |
| 57 | +### Final Steps |
| 58 | +* Create AWS Lambda |
| 59 | +* Update Handler |
| 60 | +* Test FastAPI Lambda |
| 61 | +* Create API Gateway |
| 62 | +* Create Resource |
| 63 | +* Deploy Lambda Proxy API |
| 64 | + |
| 65 | +### Summary |
| 66 | +That's it! We Created a FastAPI application and converted it to an AWS Lambda. Then we setup API Gateway to route all requests to our Lambda proxy. |
| 67 | + |
| 68 | +#### References |
| 69 | +- Simple Serverless FastAPI with AWS Lambda - [https://www.deadbear.io/simple-serverless-fastapi-with-aws-lambda/] |
0 commit comments