How to Add Python Dependencies to AWS Lambda | How to Install Python Dependencies in AWS Lambda

  • Last updated Apr 25, 2024

In this tutorial, I will explain you how to add/install Python dependencies to AWS Lambda function.

To install Python dependencies in an AWS Lambda function, do the following:

  1. Open a terminal and create a folder:
  2. mkdir mylibs
  3. Navigate inside the folder you just created:
  4. cd mylibs
  5. Create a requirements.txt file inside that folder and add all the libraries that your function needs. For Example:
  6. certifi==2021.5.30
  7. Run the following commands to install libraries compatible with your runtime in the appropriate sub folder (Replace python3.8 with the version of your Python):
  8. Note: You must have docker installed on your computer to run this command.

    Use the commands with sudo if you get permission error.

    docker run -v "$PWD":/var/task "lambci/lambda:build-python3.8" /bin/sh -c "pip3.8 install -r requirements.txt -t python/lib/python3.8/site-packages/; exit"
  9. Zip the python folder and create the layer package by running the following command:
  10. zip -r python > /dev/null
  11. Go to the AWS Lambda console > Layers. Enter the details, upload the zip file you created with and click the Create button. Refer to the image below for example:
  12. Go to your Lambda Function and scroll down until you see the option to Add a Layer as shown in the example image below:
  13. On the Add layer page, select Custom layers for Layer source. Select the layer you created from the dropdown list for Custom layers. Finally select the version and choose the Add button. Refer to the image below for example:
  14. Now, you can import modules from the libraries you added in your AWS Lambda function.