Upload ZIP to Lambda

52 Reads

The error you're seeing indicates that the requests library is not available in the AWS Lambda environment by default, so you need to include it manually. Here’s how you can do that:

Solution: Deploy requests with Your Lambda Function

  1. Create a Local Directory for Your Lambda Function: Create a directory that will hold both your Lambda function and the requests library.

    mkdir lambda_function
    cd lambda_function
    
  2. Install the requests Library Locally: You need to install the requests library and all its dependencies into this directory. Use the --target option with pip to specify the current directory.

    pip install requests -t .
    

    This command will install the requests library and all its dependencies in the current directory.

  3. Add Your Lambda Function: Create a lambda_function.py file inside the same directory where you installed the requests module. Here's an example:

    # lambda_function.py
    import requests
    
    def lambda_handler(event, context):
        response = requests.get('https://api.example.com')
        return {
            'statusCode': 200,
            'body': response.text
        }
    
  4. Zip the Directory: Once the library and your Lambda function are in the same directory, zip everything into a single file.

    zip -r lambda_function.zip .
    

    This will create a lambda_function.zip file that contains both your lambda_function.py and the requests module.

  5. Upload the Zip to AWS Lambda:

    • Go to the AWS Lambda Console.
    • Create a new function (or select an existing one).
    • In the function’s Code section, click Upload from.zip file.
    • Upload the lambda_function.zip file you just created.
  6. Test the Lambda Function: Now, test the function in the Lambda Console to verify that the requests library is working properly.

Alternative: Use AWS Lambda Layers

If you need to reuse the requests library across multiple Lambda functions, you can create an AWS Lambda Layer. Here's a brief guide for that:

  1. Install Requests Locally (in a python directory):

    mkdir python
    pip install requests -t python/
    
  2. Zip the Python Directory:

    zip -r requests_layer.zip python
    
  3. Create a Lambda Layer:

    • Go to the AWS Lambda Console.
    • Navigate to the Layers section.
    • Create a new layer by uploading the requests_layer.zip.
    • Specify the compatible runtimes (e.g., Python 3.8, 3.9, etc.).
  4. Attach the Layer to Your Lambda Function:

    • Open your Lambda function in the AWS Console.
    • Scroll down to the Layers section.
    • Add the requests layer you created.

This will allow you to keep your Lambda function code lean and reuse the requests library across multiple functions.

Let me know if you run into any issues!

#Lambda

#Tech

#AWS