AWS Lambda Error - “Unable to import module 'lambda_function': No module named 'requests'

 

AWS Lambda Error - “Unable to import module 'lambda_function': No module named 'requests'

This error is Lambda’s way of saying you forgot to bring your toolbox.





Problem

Your Lambda function fails at runtime with the error:

Unable to import module 'lambda_function': No module named 'requests'

This message appears in CloudWatch Logs immediately after deployment. The function doesn’t even reach your handler — it fails during initialization when trying to import external libraries that aren’t present in the runtime.

Clarifying the Issue

The issue isn’t with your Python code. It’s with your deployment bundle.
AWS Lambda includes only a minimal Python runtime. Libraries like requestspandas, or beautifulsoup4 are not preinstalled. You must either bundle them manually inside your ZIP file or attach them through a Lambda layer.

Why It Matters

In a CI/CD workflow, missing dependencies can halt pipelines, break integrations, and delay releases. Because Lambda initializes before your handler executes, a missing module crashes the container before any custom logic can run — meaning your CloudWatch logs won’t even contain your own print statements. Getting the packaging right ensures your functions stay portable, repeatable, and production-ready.

Key Terms

  • Deployment Package – A ZIP or container image containing your code and its dependencies.
  • Lambda Layer – A shared library bundle that can be attached to multiple Lambda functions.
  • Runtime – The specific Python environment Lambda uses to run your function.
  • Cold Start – The container startup phase when dependencies are loaded into memory.

Steps at a Glance

  1. Verify that the missing module isn’t included by default.
  2. Create a deployment package including all dependencies.
  3. (Optional) Create or attach a Lambda layer for shared libraries.
  4. Upload and redeploy the updated function.
  5. Test again and verify the import works.
  6. Handle future import errors gracefully.

Step 1: Verify that the missing module isn’t included by default

Before adding extra files, confirm the requests library truly isn’t part of the runtime.
You can do this locally in the same Python version as your Lambda function (for example, Python 3.12):

python3.12 -c "import requests; print(requests.__version__)"

Expected Output:

ModuleNotFoundError: No module named 'requests'

This confirms requests isn’t part of the standard library — it must be packaged manually.


Step 2: Create a deployment package including all dependencies

Next, install requests into a subfolder and zip it up with your Lambda code.

Command:

mkdir package
pip install requests -t ./package
cp lambda_function.py ./package
cd package
zip -r9 ../lambda_function.zip .

Output:

Adding requests/__init__.py
Adding requests/models.py
Adding lambda_function.py

⚙️ Note: Make sure you install dependencies using the same Python version as your Lambda runtime (for example, python3.12). Using a different interpreter can cause module import failures, especially for libraries with compiled extensions.

This ZIP file (lambda_function.zip) now includes both your handler and the library code. You can upload it manually via the Lambda console or push it through your CI/CD pipeline.


Step 3: (Optional) Create or attach a Lambda layer for shared libraries

If multiple functions use requests or other common packages, create a layer instead of bundling each one.

Command:

mkdir python
pip install requests -t python/
zip -r9 requests-layer.zip python
aws lambda publish-layer-version \
  --layer-name requests-layer \
  --zip-file fileb://requests-layer.zip \
  --compatible-runtimes python3.12

Output:

{
  "LayerVersionArn": "arn:aws:lambda:us-east-1:123456789012:layer:requests-layer:1",
  "CompatibleRuntimes": ["python3.12"]
}

The folder name must be python/ because AWS Lambda automatically adds /opt/python from your layer to the module search path at runtime. Any other folder name will cause your imports to fail.

You’ll see a new layer version ARN. Copy that ARN and attach it to your function in the Lambda console or CLI:

aws lambda update-function-configuration \
  --function-name myLambda \
  --layers arn:aws:lambda:us-east-1:123456789012:layer:requests-layer:1

This approach keeps your function ZIPs small and your deployments faster.


Step 4: Upload and redeploy the updated function

Now, redeploy your fixed function package (or reattach the updated layer).

Command:

aws lambda update-function-code \
  --function-name myLambda \
  --zip-file fileb://lambda_function.zip

Output:

{
  "FunctionName": "myLambda",
  "LastModified": "2025-11-11T17:45:52.789+0000",
  "RevisionId": "2e98b0f6-7c9f-4bca-bef9-2b3eabf1c1d3"
}

Once complete, Lambda will start using the new package on the next invocation.


Step 5: Test again and verify the import works

Finally, test your function using the console or CLI to confirm the error is resolved.

Command:

aws lambda invoke \
  --function-name myLambda \
  --payload '{}' \
  response.json
cat response.json

Output:

{"statusCode": 200, "body": "Lambda executed successfully"}

Check CloudWatch Logs — the “Unable to import module” message should be gone.


Step 6: Handle future import errors gracefully

If you ever see a similar error in another environment or during partial deployments, add a short safeguard to help diagnose the problem quickly before redeploying.

try:
    import requests
except ImportError as e:
    print("Dependency error:", e)
    raise RuntimeError("Missing dependency: requests") from e

Explanation:
This defensive block doesn’t solve the packaging problem — but it exposes the root cause faster. Instead of Lambda failing silently or cryptically, you’ll get a clear log line showing exactly which dependency is missing. That clarity shortens your triage loop in staging and helps your CI/CD team pinpoint broken layers or ZIP builds.

Note: This safeguard only catches imports that occur after the Lambda environment initializes. It won’t intercept the pre-handler initialization failure described in Step One — that can only be fixed by repackaging your dependencies (Steps Two and Three).


Pro Tips

  • Always build your ZIP on the same OS and architecture as the Lambda runtime (Amazon Linux). Using Docker or sam build ensures compatibility.
  • Consider container images for complex dependencies — you can define everything in a Dockerfile and skip zipping altogether.
  • Keep library versions pinned in requirements.txt so CI/CD deployments remain consistent.
  • For large shared dependencies (e.g., Pandas, NumPy), always prefer Lambda layers to reduce function size.
  • For simple HTTP calls, consider using the built-in urllib.request or boto3 (already included in Lambda) to avoid extra dependencies.

Conclusion

This error is Lambda’s way of saying, “You forgot to bring your toolbox.”
By packaging dependencies correctly — either in the ZIP or a layer — you ensure your functions initialize cleanly and run predictably across environments. The next time CloudWatch throws No module named 'requests', you’ll know exactly what to do.


Aaron Rose is a software engineer and technology writer at tech-reader.blog and the author of Think Like a Genius.

Comments

Popular posts from this blog

The New ChatGPT Reason Feature: What It Is and Why You Should Use It

Insight: The Great Minimal OS Showdown—DietPi vs Raspberry Pi OS Lite

Raspberry Pi Connect vs. RealVNC: A Comprehensive Comparison