Lambda functions are stateless and ephemeral, meaning they don’t retain any information or code between invocations. To run your Python code, Lambda needs all its dependencies bundled together in a deployment package.

Here’s a Python Lambda function that makes an HTTP request using the requests library:

import json
import requests

def lambda_handler(event, context):
    try:
        response = requests.get('https://httpbin.org/get')
        response.raise_for_status()  # Raise an exception for bad status codes
        data = response.json()
        
        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': 'Successfully fetched data',
                'data': data
            })
        }
    except requests.exceptions.RequestException as e:
        return {
            'statusCode': 500,
            'body': json.dumps({
                'message': 'Error fetching data',
                'error': str(e)
            })
        }

To deploy this, you need to package lambda_function.py along with the requests library. The simplest way to create this deployment package is using the zip command.

First, create a directory for your project and navigate into it:

mkdir lambda_project
cd lambda_project

Next, create your Lambda function file (lambda_function.py) inside this directory. Then, install the requests library into the same directory:

pip install requests -t .

The -t . flag tells pip to install the package and its dependencies directly into the current directory. Now, your lambda_project directory should contain lambda_function.py and a requests folder (and potentially other folders and files for requests’ dependencies like urllib3, charset_normalizer, etc.).

Finally, create a ZIP archive of everything in the directory, excluding the directory itself:

zip -r ../lambda_deployment_package.zip .

This command creates lambda_deployment_package.zip in the parent directory, containing all your code and dependencies. You can then upload this ZIP file to Lambda.

When Lambda executes your function, it unpacks this ZIP file into a temporary directory and adds that directory to Python’s sys.path. This allows your function code to import requests as if it were installed system-wide.

The most common pitfall is not installing dependencies into the same directory as your handler code, or zipping the parent directory instead of its contents. For instance, if you zip lambda_project instead of its contents, Lambda will see a lambda_project folder inside the zip, and won’t be able to find your lambda_function.py at the root.

The next hurdle you’ll often encounter is managing larger dependencies or native compiled libraries, which require a different packaging strategy, often involving Lambda Layers or container images.

Want structured learning?

Take the full Lambda course →