AWS Lambda to MySQL and API Gateway

Posted under » Python » AWS on 24 May 2021

Why do you need Lambda to access RDS? Well there is no server involved and it is suited for high availability. Let's try it out.

To create a REST API we create the Lambda function first, not the other way round.

Give the function a sensible name, runtime (Python 3.9) and architecture (x86_e4)

Under permission, choose an execution role. You need to have the permission to execute the function. It is an AIM role attached to the lambda function. Your AIM settings must be able to create a role. The basic role allows us to upload logs to AWS Cloudwatch logs.

Once you have successfully created the function, a dunny function is also created and you can test it.

Since no server is involved, you need to have all the python dependencies that the function requires.

Now it is time to put your code.

If you add the package to the layer via pip from Windows/MacOS machine, it would not be compatible with AWS Lambda Python runtime. In that case, you need to download the wheel file for Linux (from PyPi), extract it, and the use that for your AWS Lambda layer. On top of that, you also need to find the wheel file for the package dependencies too. For example, if you want to use pandas, you also need to download: numpy, pytz, python-dateutil. Again, if you want to use python-dateutil, you would also need to download six packages.

All of that hassle can be very easily done in Linux environment. Installing packages via pip3 command will also pull the dependencies.

The directory tree should contain python/lib/python3.8/site-packages(site directories) and the bin folder.

One of the most important package when you want to connect to MySQL is the pymysql.

You should exclude "__pycache__"

Should you be missing a package, an error message will alert you. Typically, I will load my lambda function via a zip file. So if I am missing a package, I will rezip with the missing python package and upload again. This will overwrite everything.

If your get an errorMessage: Unable to import module 'lambda_function': No module named 'lambda_function', it means your python file name is different from the one specified in the "def lambda_handler(event, context):".

To make this error message go away, go to the 'code' tab, scroll down and go to runtime settings. and change it to 'lambda_function_mth108b.lambda_handler' if your python file is 'lambda_function_mth108b.py'

Once you have created it, you can test it. If it works well, then you can link it to your REST API.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data