AWS Lambda Python Integration Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture. Overview AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations. When to Use Use this skill when: - Creating new Lambda functions in Python - Migrating existing Python applications to Lambda - Optimizing cold start performance for Python Lambda - Choosing between framework-based and minimal Python ap…

: 'list_users',\n r'^GET /users/(?P\u003cuser_id>[^/]+)

AWS Lambda Python Integration Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture. Overview AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations. When to Use Use this skill when: - Creating new Lambda functions in Python - Migrating existing Python applications to Lambda - Optimizing cold start performance for Python Lambda - Choosing between framework-based and minimal Python ap…

: 'get_user',\n r'^POST /users

AWS Lambda Python Integration Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture. Overview AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations. When to Use Use this skill when: - Creating new Lambda functions in Python - Migrating existing Python applications to Lambda - Optimizing cold start performance for Python Lambda - Choosing between framework-based and minimal Python ap…

: 'create_user',\n r'^PUT /users/(?P\u003cuser_id>[^/]+)

AWS Lambda Python Integration Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture. Overview AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations. When to Use Use this skill when: - Creating new Lambda functions in Python - Migrating existing Python applications to Lambda - Optimizing cold start performance for Python Lambda - Choosing between framework-based and minimal Python ap…

: 'update_user',\n r'^DELETE /users/(?P\u003cuser_id>[^/]+)

AWS Lambda Python Integration Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture. Overview AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations. When to Use Use this skill when: - Creating new Lambda functions in Python - Migrating existing Python applications to Lambda - Optimizing cold start performance for Python Lambda - Choosing between framework-based and minimal Python ap…

: 'delete_user',\n}\n\ndef lambda_handler(event, context):\n \"\"\"Main router for API Gateway requests.\"\"\"\n http_method = event.get('httpMethod', 'GET')\n path = event.get('path', '/')\n\n # Match route\n route_key = f\"{http_method} {path}\"\n\n for pattern, handler_name in ROUTES.items():\n match = re.match(pattern, route_key)\n if match:\n handler = globals()[handler_name]\n return handler(event, context, **match.groupdict())\n\n return response(404, {'error': 'Not found'})\n\ndef list_users(event, context):\n \"\"\"GET /users\"\"\"\n # Implementation here\n return response(200, {'users': []})\n\ndef get_user(event, context, user_id):\n \"\"\"GET /users/{user_id}\"\"\"\n return response(200, {'user_id': user_id})\n\ndef create_user(event, context):\n \"\"\"POST /users\"\"\"\n body = json.loads(event.get('body', '{}'))\n return response(201, {'created': body})\n\ndef update_user(event, context, user_id):\n \"\"\"PUT /users/{user_id}\"\"\"\n body = json.loads(event.get('body', '{}'))\n return response(200, {'updated': user_id, 'data': body})\n\ndef delete_user(event, context, user_id):\n \"\"\"DELETE /users/{user_id}\"\"\"\n return response(200, {'deleted': user_id})\n\ndef response(status_code, body, headers=None):\n \"\"\"Helper for API Gateway responses.\"\"\"\n default_headers = {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*'\n }\n if headers:\n default_headers.update(headers)\n\n return {\n 'statusCode': status_code,\n 'headers': default_headers,\n 'body': json.dumps(body)\n }\n```\n\n### Request/Response Helpers\n\n```python\n# lambda_function.py\nimport json\nfrom typing import Dict, Any, Optional\n\nclass APIGatewayRequest:\n \"\"\"Wrapper for API Gateway events.\"\"\"\n\n def __init__(self, event: Dict[str, Any]):\n self.event = event\n self.method = event.get('httpMethod', 'GET')\n self.path = event.get('path', '/')\n self.query_params = event.get('queryStringParameters') or {}\n self.path_params = event.get('pathParameters') or {}\n self.headers = {k.lower(): v for k, v in (event.get('headers') or {}).items()}\n\n body = event.get('body')\n self.body = json.loads(body) if body and event.get('isBase64Encoded') else body\n\n def get_header(self, name: str, default: str = None) -> Optional[str]:\n return self.headers.get(name.lower(), default)\n\n def get_query(self, name: str, default: str = None) -> Optional[str]:\n return self.query_params.get(name, default)\n\nclass APIGatewayResponse:\n \"\"\"Builder for API Gateway responses.\"\"\"\n\n def __init__(self):\n self.status_code = 200\n self.headers = {'Content-Type': 'application/json'}\n self.body = {}\n\n def status(self, code: int) -> 'APIGatewayResponse':\n self.status_code = code\n return self\n\n def header(self, name: str, value: str) -> 'APIGatewayResponse':\n self.headers[name] = value\n return self\n\n def json(self, data: Dict) -> Dict[str, Any]:\n return {\n 'statusCode': self.status_code,\n 'headers': self.headers,\n 'body': json.dumps(data)\n }\n\n def text(self, text: str) -> Dict[str, Any]:\n self.headers['Content-Type'] = 'text/plain'\n return {\n 'statusCode': self.status_code,\n 'headers': self.headers,\n 'body': text\n }\n\n# Usage\ndef lambda_handler(event, context):\n request = APIGatewayRequest(event)\n\n if request.method == 'GET':\n return APIGatewayResponse().json({'path': request.path})\n\n return APIGatewayResponse().status(405).json({'error': 'Method not allowed'})\n```\n\n## Error Handling\n\n### Structured Error Responses\n\n```python\n# lambda_function.py\nimport json\nimport traceback\nfrom typing import Dict, Any\n\nclass LambdaError(Exception):\n \"\"\"Custom error with HTTP status code.\"\"\"\n\n def __init__(self, message: str, status_code: int = 500, details: Dict = None):\n self.message = message\n self.status_code = status_code\n self.details = details or {}\n super().__init__(message)\n\nclass ValidationError(LambdaError):\n def __init__(self, message: str, details: Dict = None):\n super().__init__(message, 400, details)\n\nclass NotFoundError(LambdaError):\n def __init__(self, message: str):\n super().__init__(message, 404)\n\ndef error_response(error: LambdaError, request_id: str = None) -> Dict[str, Any]:\n \"\"\"Format error for API Gateway response.\"\"\"\n return {\n 'statusCode': error.status_code,\n 'headers': {'Content-Type': 'application/json'},\n 'body': json.dumps({\n 'error': error.__class__.__name__,\n 'message': error.message,\n 'details': error.details,\n 'requestId': request_id\n })\n }\n\ndef lambda_handler(event, context):\n \"\"\"Handler with centralized error handling.\"\"\"\n try:\n return process_request(event, context)\n except LambdaError as e:\n return error_response(e, context.aws_request_id)\n except Exception as e:\n # Log full traceback for debugging\n print(f\"Unhandled error: {traceback.format_exc()}\")\n return error_response(\n LambdaError(\"Internal server error\"),\n context.aws_request_id\n )\n\ndef process_request(event, context):\n \"\"\"Main request processing logic.\"\"\"\n user_id = event.get('pathParameters', {}).get('user_id')\n\n if not user_id:\n raise ValidationError(\"user_id is required\")\n\n user = find_user(user_id)\n if not user:\n raise NotFoundError(f\"User {user_id} not found\")\n\n return {\n 'statusCode': 200,\n 'headers': {'Content-Type': 'application/json'},\n 'body': json.dumps({'user': user})\n }\n\ndef find_user(user_id: str) -> Dict:\n # Implementation\n return None\n```\n\n## Context Usage\n\n### Lambda Context Object\n\n```python\n# lambda_function.py\n\ndef lambda_handler(event, context):\n \"\"\"Demonstrate context object usage.\"\"\"\n context_info = {\n # Identity\n 'function_name': context.function_name,\n 'function_version': context.function_version,\n 'memory_limit_mb': context.memory_limit_in_mb,\n 'aws_request_id': context.aws_request_id,\n 'invoked_function_arn': context.invoked_function_arn,\n 'log_group_name': context.log_group_name,\n 'log_stream_name': context.log_stream_name,\n\n # Timing\n 'remaining_time_ms': context.get_remaining_time_in_millis(),\n }\n\n # Check if we have enough time\n if context.get_remaining_time_in_millis() \u003c 1000:\n print(\"Warning: Running low on time!\")\n\n # Identity (for Cognito authorizer)\n if hasattr(context, 'identity'):\n context_info['identity'] = {\n 'cognito_identity_id': context.identity.cognito_identity_id,\n 'cognito_identity_pool_id': context.identity.cognito_identity_pool_id,\n }\n\n # Client context (for mobile SDK)\n if hasattr(context, 'client_context'):\n context_info['client_context'] = context.client_context\n\n return {\n 'statusCode': 200,\n 'body': json.dumps(context_info)\n }\n```\n\n## Environment Configuration\n\n### Configuration Class\n\n```python\n# config.py\nimport os\nfrom typing import List\n\nclass Config:\n \"\"\"Configuration management with validation.\"\"\"\n\n # Required environment variables\n REQUIRED = ['TABLE_NAME']\n\n # Optional with defaults\n DEBUG: bool = os.environ.get('DEBUG', 'false').lower() == 'true'\n REGION: str = os.environ.get('AWS_REGION', 'us-east-1')\n LOG_LEVEL: str = os.environ.get('LOG_LEVEL', 'INFO')\n TABLE_NAME: str = os.environ.get('TABLE_NAME', '')\n BUCKET_NAME: str = os.environ.get('BUCKET_NAME', '')\n\n # Numeric values\n TIMEOUT_SECONDS: int = int(os.environ.get('TIMEOUT_SECONDS', '30'))\n MAX_RETRIES: int = int(os.environ.get('MAX_RETRIES', '3'))\n\n # Lists\n ALLOWED_ORIGINS: List[str] = os.environ.get('ALLOWED_ORIGINS', '*').split(',')\n\n @classmethod\n def validate(cls) -> None:\n \"\"\"Validate required configuration.\"\"\"\n missing = []\n for var in cls.REQUIRED:\n if not getattr(cls, var):\n missing.append(var)\n\n if missing:\n raise ValueError(f\"Missing required environment variables: {missing}\")\n\n @classmethod\n def to_dict(cls) -> dict:\n \"\"\"Export configuration as dictionary.\"\"\"\n return {\n 'DEBUG': cls.DEBUG,\n 'REGION': cls.REGION,\n 'LOG_LEVEL': cls.LOG_LEVEL,\n 'TABLE_NAME': cls.TABLE_NAME,\n 'BUCKET_NAME': cls.BUCKET_NAME,\n 'TIMEOUT_SECONDS': cls.TIMEOUT_SECONDS,\n 'MAX_RETRIES': cls.MAX_RETRIES,\n }\n\n# lambda_function.py\nfrom config import Config\n\n# Validate on module load\nConfig.validate()\n\ndef lambda_handler(event, context):\n if Config.DEBUG:\n print(f\"Config: {Config.to_dict()}\")\n\n return {'statusCode': 200, 'config': Config.to_dict()}\n```\n\n## Logging\n\n### Structured Logging\n\n```python\n# lambda_function.py\nimport json\nimport logging\nfrom datetime import datetime, timezone\n\n# Configure logger\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nclass StructuredLog:\n \"\"\"Structured logging for CloudWatch.\"\"\"\n\n @staticmethod\n def info(message: str, **kwargs):\n log_entry = {\n 'timestamp': datetime.now(timezone.utc).isoformat(),\n 'level': 'INFO',\n 'message': message,\n **kwargs\n }\n logger.info(json.dumps(log_entry))\n\n @staticmethod\n def error(message: str, error: Exception = None, **kwargs):\n log_entry = {\n 'timestamp': datetime.now(timezone.utc).isoformat(),\n 'level': 'ERROR',\n 'message': message,\n **kwargs\n }\n if error:\n log_entry['error_type'] = error.__class__.__name__\n log_entry['error_message'] = str(error)\n\n logger.error(json.dumps(log_entry))\n\n @staticmethod\n def metric(name: str, value: float, unit: str = 'Count'):\n \"\"\"Emit CloudWatch metric via log.\"\"\"\n log_entry = {\n '_aws': {\n 'Timestamp': int(datetime.now(timezone.utc).timestamp() * 1000),\n 'CloudWatchMetrics': [{\n 'Namespace': 'Lambda/Custom',\n 'Dimensions': [['FunctionName']],\n 'Metrics': [{'Name': name, 'Unit': unit}]\n }]\n },\n 'FunctionName': os.environ.get('AWS_LAMBDA_FUNCTION_NAME', 'unknown'),\n name: value\n }\n logger.info(json.dumps(log_entry))\n\n# Usage\ndef lambda_handler(event, context):\n StructuredLog.info(\n 'Processing request',\n request_id=context.aws_request_id,\n path=event.get('path')\n )\n\n try:\n result = process_event(event)\n StructuredLog.metric('SuccessCount', 1)\n return {'statusCode': 200, 'body': result}\n except Exception as e:\n StructuredLog.error('Processing failed', error=e)\n StructuredLog.metric('ErrorCount', 1)\n raise\n```\n\n## Deployment Packaging\n\n### requirements.txt\n\n```txt\n# Minimal requirements for raw Python Lambda\nboto3>=1.35.0\n\n# Add only what you need\nrequests>=2.32.0 # For HTTP calls\npydantic>=2.5.0 # For data validation\n```\n\n### Build Script\n\n```bash\n#!/bin/bash\n# build.sh - Build deployment package\n\nset -e\n\nPACKAGE_DIR=\"package\"\nOUTPUT=\"deployment.zip\"\n\n# Clean previous builds\nrm -rf $PACKAGE_DIR $OUTPUT\n\n# Install dependencies\npip install -r requirements.txt -t $PACKAGE_DIR\n\n# Copy source code\ncp lambda_function.py config.py $PACKAGE_DIR/\n\n# Create zip\ncd $PACKAGE_DIR\nzip -r ../$OUTPUT .\ncd ..\n\necho \"Created $OUTPUT\"\n```\n\n## Best Practices\n\n1. **Keep handlers small** - Delegate to separate functions/classes\n2. **Initialize outside handler** - Module-level for warm start reuse\n3. **Use lazy loading** - Defer heavy imports until needed\n4. **Handle timeouts** - Check `context.get_remaining_time_in_millis()`\n5. **Validate input** - Always check event structure\n6. **Use structured logging** - JSON for CloudWatch Insights\n7. **Environment configuration** - No hardcoded values\n8. **Error handling** - Graceful degradation with proper HTTP codes\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":16381,"content_sha256":"15f76685e741b10cf865068594796792b4da274c3d33791329d5ed8fbd0d7148"},{"filename":"references/serverless-deployment.md","content":"# Serverless Deployment for Python Lambda\n\nDeployment patterns for Python Lambda functions using Serverless Framework, AWS SAM, and CI/CD pipelines.\n\n## Serverless Framework\n\n### Basic Configuration\n\n```yaml\n# serverless.yml\nservice: my-python-api\n\nprovider:\n name: aws\n runtime: python3.12 # or python3.11\n stage: ${opt:stage, 'dev'}\n region: ${opt:region, 'us-east-1'}\n memorySize: 256\n timeout: 10\n\n # Environment variables for all functions\n environment:\n STAGE: ${self:provider.stage}\n REGION: ${self:provider.region}\n TABLE_NAME: ${self:service}-table-${self:provider.stage}\n\n # IAM permissions\n iam:\n role:\n statements:\n - Effect: Allow\n Action:\n - logs:CreateLogGroup\n - logs:CreateLogStream\n - logs:PutLogEvents\n Resource: '*'\n\nfunctions:\n api:\n handler: lambda_function.lambda_handler\n events:\n - http:\n path: /{proxy+}\n method: ANY\n cors: true\n```\n\n### Advanced Configuration\n\n```yaml\n# serverless.yml\nservice: my-python-api\n\nprovider:\n name: aws\n runtime: python3.12 # or python3.11\n stage: ${opt:stage, 'dev'}\n region: ${opt:region, 'us-east-1'}\n memorySize: 256\n timeout: 10\n logRetentionInDays: 14\n versionFunctions: false\n\n # VPC configuration\n vpc:\n securityGroupIds:\n - sg-xxxxxxxx\n subnetIds:\n - subnet-xxxxxxxx\n - subnet-yyyyyyyy\n\n # Environment variables\n environment:\n STAGE: ${self:provider.stage}\n REGION: ${self:provider.region}\n TABLE_NAME: !Ref UsersTable\n BUCKET_NAME: !Ref AssetsBucket\n\n # IAM role statements\n iam:\n role:\n name: ${self:service}-${self:provider.stage}-role\n statements:\n # DynamoDB permissions\n - Effect: Allow\n Action:\n - dynamodb:GetItem\n - dynamodb:PutItem\n - dynamodb:UpdateItem\n - dynamodb:DeleteItem\n - dynamodb:Query\n - dynamodb:Scan\n Resource:\n - !GetAtt UsersTable.Arn\n - !Sub \"${UsersTable.Arn}/index/*\"\n\n # S3 permissions\n - Effect: Allow\n Action:\n - s3:GetObject\n - s3:PutObject\n - s3:DeleteObject\n Resource:\n - !Sub \"${AssetsBucket.Arn}/*\"\n\n # CloudWatch permissions\n - Effect: Allow\n Action:\n - cloudwatch:PutMetricData\n Resource: '*'\n\n # API Gateway settings\n apiGateway:\n binaryMediaTypes:\n - 'multipart/form-data'\n minimumCompressionSize: 1024\n\nplugins:\n - serverless-python-requirements\n - serverless-offline\n\ncustom:\n pythonRequirements:\n dockerizePip: true\n slim: true\n strip: false\n layer: false\n\n serverless-offline:\n httpPort: 3000\n lambdaPort: 3002\n\npackage:\n individually: false\n patterns:\n - '!.git/**'\n - '!.gitignore'\n - '!.DS_Store'\n - '!node_modules/**'\n - '!.pytest_cache/**'\n - '!tests/**'\n - '!.env'\n - '!.venv/**'\n - '!venv/**'\n - '!__pycache__/**'\n - '!.mypy_cache/**'\n\nfunctions:\n api:\n handler: lambda_function.lambda_handler\n description: Main API handler\n memorySize: 512\n timeout: 30\n reservedConcurrency: 100\n provisionedConcurrency: 10\n environment:\n FUNCTION_NAME: api\n events:\n - http:\n path: /{proxy+}\n method: ANY\n cors:\n origin: '*'\n headers:\n - Content-Type\n - Authorization\n - X-Amz-Date\n - X-Api-Key\n - X-Amz-Security-Token\n allowCredentials: true\n\n scheduled-task:\n handler: handlers.scheduled_task\n description: Daily scheduled task\n events:\n - schedule: rate(1 day)\n\n sqs-processor:\n handler: handlers.process_sqs_message\n description: SQS message processor\n reservedConcurrency: 50\n events:\n - sqs:\n arn: !GetAtt MessageQueue.Arn\n batchSize: 10\n maximumBatchingWindowInSeconds: 5\n\nresources:\n Resources:\n UsersTable:\n Type: AWS::DynamoDB::Table\n Properties:\n TableName: ${self:service}-users-${self:provider.stage}\n BillingMode: PAY_PER_REQUEST\n AttributeDefinitions:\n - AttributeName: id\n AttributeType: S\n - AttributeName: email\n AttributeType: S\n KeySchema:\n - AttributeName: id\n KeyType: HASH\n GlobalSecondaryIndexes:\n - IndexName: email-index\n KeySchema:\n - AttributeName: email\n KeyType: HASH\n Projection:\n ProjectionType: ALL\n\n AssetsBucket:\n Type: AWS::S3::Bucket\n Properties:\n BucketName: ${self:service}-assets-${self:provider.stage}\n PublicAccessBlockConfiguration:\n BlockPublicAcls: true\n BlockPublicPolicy: true\n IgnorePublicAcls: true\n RestrictPublicBuckets: true\n\n MessageQueue:\n Type: AWS::SQS::Queue\n Properties:\n QueueName: ${self:service}-messages-${self:provider.stage}\n VisibilityTimeout: 300\n\n Outputs:\n ApiGatewayRestApiId:\n Value: !Ref ApiGatewayRestApi\n Export:\n Name: ${self:service}-${self:provider.stage}-restApiId\n\n ApiGatewayRestApiRootResourceId:\n Value: !GetAtt ApiGatewayRestApi.RootResourceId\n Export:\n Name: ${self:service}-${self:provider.stage}-rootResourceId\n```\n\n### Commands\n\n```bash\n# Install plugins\nnpm install\n\n# Deploy to dev\nserverless deploy\n\n# Deploy to specific stage\nserverless deploy --stage prod\n\n# Deploy specific function\nserverless deploy function -f api\n\n# Invoke locally\nserverless invoke local -f api -p event.json\n\n# View logs\nserverless logs -f api --tail\n\n# Remove stack\nserverless remove\n```\n\n## AWS SAM\n\n### Basic Template\n\n```yaml\n# template.yaml\nAWSTemplateFormatVersion: '2010-09-09'\nTransform: AWS::Serverless-2016-10-31\nDescription: Python Lambda API\n\nGlobals:\n Function:\n Timeout: 10\n MemorySize: 256\n Runtime: python3.12 # or python3.11\n Architectures:\n - x86_64\n Environment:\n Variables:\n LOG_LEVEL: INFO\n\nParameters:\n Stage:\n Type: String\n Default: dev\n AllowedValues:\n - dev\n - staging\n - prod\n\nConditions:\n IsProd: !Equals [!Ref Stage, prod]\n\nResources:\n ApiFunction:\n Type: AWS::Serverless::Function\n Properties:\n CodeUri: ./\n Handler: lambda_function.lambda_handler\n Description: Main API handler\n MemorySize: 512\n Timeout: 30\n AutoPublishAlias: live\n ProvisionedConcurrencyConfig:\n !If [IsProd, {ProvisionedConcurrentExecutions: 10}, !Ref \"AWS::NoValue\"]\n Environment:\n Variables:\n TABLE_NAME: !Ref UsersTable\n STAGE: !Ref Stage\n Events:\n ApiEvent:\n Type: Api\n Properties:\n Path: /{proxy+}\n Method: ANY\n RestApiId: !Ref ApiGatewayApi\n Policies:\n - DynamoDBCrudPolicy:\n TableName: !Ref UsersTable\n\n ApiGatewayApi:\n Type: AWS::Serverless::Api\n Properties:\n StageName: !Ref Stage\n Cors:\n AllowMethods: \"'GET,POST,PUT,DELETE,OPTIONS'\"\n AllowHeaders: \"'Content-Type,Authorization'\"\n AllowOrigin: \"'*'\"\n MaxAge: \"'600'\"\n\n UsersTable:\n Type: AWS::DynamoDB::Table\n Properties:\n TableName: !Sub \"${AWS::StackName}-users\"\n BillingMode: PAY_PER_REQUEST\n AttributeDefinitions:\n - AttributeName: id\n AttributeType: S\n KeySchema:\n - AttributeName: id\n KeyType: HASH\n\nOutputs:\n ApiUrl:\n Description: API Gateway endpoint URL\n Value: !Sub \"https://${ApiGatewayApi}.execute-api.${AWS::Region}.amazonaws.com/${Stage}/\"\n\n ApiFunctionArn:\n Description: Lambda function ARN\n Value: !GetAtt ApiFunction.Arn\n```\n\n### SAM with Lambda Layers\n\n```yaml\n# template.yaml\nAWSTemplateFormatVersion: '2010-09-09'\nTransform: AWS::Serverless-2016-10-31\n\nGlobals:\n Function:\n Timeout: 10\n Runtime: python3.12 # or python3.11\n Layers:\n - !Ref DependenciesLayer\n\nResources:\n DependenciesLayer:\n Type: AWS::Serverless::LayerVersion\n Properties:\n LayerName: python-dependencies\n Description: Common Python dependencies\n ContentUri: dependencies/\n CompatibleRuntimes:\n - python3.12\n - python3.10\n RetentionPolicy: Retain\n Metadata:\n BuildMethod: python3.12\n\n ApiFunction:\n Type: AWS::Serverless::Function\n Properties:\n CodeUri: src/\n Handler: app.lambda_handler\n Environment:\n Variables:\n TABLE_NAME: !Ref UsersTable\n Events:\n ApiEvent:\n Type: Api\n Properties:\n Path: /{proxy+}\n Method: ANY\n```\n\n### SAM Commands\n\n```bash\n# Build the application\nsam build\n\n# Build with specific runtime\nsam build --use-container\n\n# Local invoke\nsam local invoke ApiFunction -e events/api.json\n\n# Local API server\nsam local start-api\n\n# Validate template\nsam validate\n\n# Deploy (guided)\nsam deploy --guided\n\n# Deploy (CI/CD)\nsam deploy \\\n --stack-name my-stack \\\n --s3-bucket my-deployment-bucket \\\n --region us-east-1 \\\n --capabilities CAPABILITY_IAM \\\n --parameter-overrides Stage=prod\n\n# Delete stack\nsam delete\n```\n\n## AWS Chalice Deployment\n\n### Chalice Config\n\n```json\n{\n \"version\": \"2.0\",\n \"app_name\": \"my-api\",\n \"stages\": {\n \"dev\": {\n \"api_gateway_stage\": \"api\",\n \"environment_variables\": {\n \"DEBUG\": \"true\"\n },\n \"lambda_functions\": {\n \"api_handler\": {\n \"lambda_timeout\": 10,\n \"lambda_memory_size\": 256,\n \"tags\": {\n \"Environment\": \"dev\"\n }\n }\n }\n },\n \"prod\": {\n \"api_gateway_stage\": \"api\",\n \"environment_variables\": {\n \"DEBUG\": \"false\"\n },\n \"lambda_functions\": {\n \"api_handler\": {\n \"lambda_timeout\": 30,\n \"lambda_memory_size\": 512,\n \"reserved_concurrent_executions\": 100,\n \"provisioned_concurrency\": 10\n }\n },\n \"tags\": {\n \"Environment\": \"prod\"\n }\n }\n }\n}\n```\n\n### Chalice Deployment Commands\n\n```bash\n# Deploy to dev\nchalice deploy\n\n# Deploy to prod\nchalice deploy --stage prod\n\n# Generate CloudFormation template\nchalice package --stage prod ./out\n\n# Deploy with CloudFormation\ncd out\naws cloudformation deploy \\\n --template-file sam.json \\\n --stack-name my-api-prod \\\n --capabilities CAPABILITY_IAM\n```\n\n## CI/CD Pipelines\n\n### GitHub Actions - SAM\n\n```yaml\n# .github/workflows/deploy.yml\nname: Deploy Lambda\n\non:\n push:\n branches: [main]\n pull_request:\n branches: [main]\n\nenv:\n AWS_REGION: us-east-1\n PYTHON_VERSION: '3.11'\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - name: Set up Python\n uses: actions/setup-python@v5\n with:\n python-version: ${{ env.PYTHON_VERSION }}\n\n - name: Cache pip dependencies\n uses: actions/cache@v4\n with:\n path: ~/.cache/pip\n key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}\n\n - name: Install dependencies\n run: |\n pip install -r requirements.txt\n pip install -r requirements-dev.txt\n\n - name: Run linting\n run: |\n flake8 .\n black --check .\n isort --check-only .\n\n - name: Run type checking\n run: mypy .\n\n - name: Run tests\n run: pytest --cov=. --cov-report=xml\n\n - name: Upload coverage\n uses: codecov/codecov-action@v4\n with:\n files: ./coverage.xml\n token: ${{ secrets.CODECOV_TOKEN }}\n\n deploy-dev:\n needs: test\n runs-on: ubuntu-latest\n if: github.ref == 'refs/heads/main'\n environment: dev\n steps:\n - uses: actions/checkout@v4\n\n - name: Configure AWS credentials\n uses: aws-actions/configure-aws-credentials@v4\n with:\n aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n aws-region: ${{ env.AWS_REGION }}\n\n - name: Set up Python\n uses: actions/setup-python@v5\n with:\n python-version: ${{ env.PYTHON_VERSION }}\n\n - name: Install SAM CLI\n run: |\n pip install aws-sam-cli\n\n - name: Build\n run: sam build --use-container\n\n - name: Deploy to Dev\n run: |\n sam deploy \\\n --stack-name my-api-dev \\\n --s3-bucket ${{ secrets.DEPLOYMENT_BUCKET }} \\\n --region ${{ env.AWS_REGION }} \\\n --capabilities CAPABILITY_IAM \\\n --parameter-overrides Stage=dev \\\n --no-confirm-changeset \\\n --no-fail-on-empty-changeset\n\n deploy-prod:\n needs: deploy-dev\n runs-on: ubuntu-latest\n if: github.ref == 'refs/heads/main'\n environment: prod\n steps:\n - uses: actions/checkout@v4\n\n - name: Configure AWS credentials\n uses: aws-actions/configure-aws-credentials@v4\n with:\n aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n aws-region: ${{ env.AWS_REGION }}\n\n - name: Set up Python\n uses: actions/setup-python@v5\n with:\n python-version: ${{ env.PYTHON_VERSION }}\n\n - name: Install SAM CLI\n run: |\n pip install aws-sam-cli\n\n - name: Build\n run: sam build --use-container\n\n - name: Deploy to Prod\n run: |\n sam deploy \\\n --stack-name my-api-prod \\\n --s3-bucket ${{ secrets.DEPLOYMENT_BUCKET }} \\\n --region ${{ env.AWS_REGION }} \\\n --capabilities CAPABILITY_IAM \\\n --parameter-overrides Stage=prod \\\n --no-confirm-changeset \\\n --no-fail-on-empty-changeset\n```\n\n### GitHub Actions - Serverless Framework\n\n```yaml\n# .github/workflows/deploy-serverless.yml\nname: Deploy with Serverless\n\non:\n push:\n branches: [main]\n\nenv:\n NODE_VERSION: '18'\n PYTHON_VERSION: '3.11'\n\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - name: Set up Python\n uses: actions/setup-python@v5\n with:\n python-version: ${{ env.PYTHON_VERSION }}\n\n - name: Install dependencies\n run: |\n pip install -r requirements.txt\n pip install pytest\n\n - name: Run tests\n run: pytest\n\n deploy:\n needs: test\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n\n - name: Set up Node.js\n uses: actions/setup-node@v4\n with:\n node-version: ${{ env.NODE_VERSION }}\n\n - name: Set up Python\n uses: actions/setup-python@v5\n with:\n python-version: ${{ env.PYTHON_VERSION }}\n\n - name: Install Serverless\n run: npm install -g serverless\n\n - name: Install plugins\n run: npm install\n\n - name: Configure AWS credentials\n uses: aws-actions/configure-aws-credentials@v4\n with:\n aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}\n aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}\n aws-region: us-east-1\n\n - name: Deploy to Dev\n if: github.ref != 'refs/heads/main'\n run: serverless deploy --stage dev\n\n - name: Deploy to Prod\n if: github.ref == 'refs/heads/main'\n run: serverless deploy --stage prod\n```\n\n## Deployment Best Practices\n\n### Stages and Environments\n\n```yaml\n# serverless.yml\nprovider:\n stage: ${opt:stage, 'dev'}\n\n environment:\n STAGE: ${self:provider.stage}\n LOG_LEVEL: ${self:custom.logLevel.${self:provider.stage}}\n\ncustom:\n logLevel:\n dev: DEBUG\n staging: INFO\n prod: WARN\n```\n\n### Secrets Management\n\n```yaml\n# serverless.yml\nprovider:\n environment:\n DATABASE_URL: ${ssm:/${self:service}/${self:provider.stage}/database-url}\n API_KEY: ${ssm:/${self:service}/${self:provider.stage}/api-key~true} # SecureString\n```\n\n### Rollback Strategy\n\n```yaml\n# serverless.yml\nprovider:\n versionFunctions: true\n deploymentSettings:\n alias: live\n type: AllAtOnce\n # For canary deployment:\n # type: Canary10Percent5Minutes\n```\n\n### Monitoring and Alarms\n\n```yaml\n# serverless.yml\nresources:\n Resources:\n ErrorAlarm:\n Type: AWS::CloudWatch::Alarm\n Properties:\n AlarmName: ${self:service}-${self:provider.stage}-errors\n MetricName: Errors\n Namespace: AWS/Lambda\n Statistic: Sum\n Period: 60\n EvaluationPeriods: 1\n Threshold: 1\n ComparisonOperator: GreaterThanOrEqualToThreshold\n Dimensions:\n - Name: FunctionName\n Value: ${self:service}-${self:provider.stage}-api\n```\n\n## Comparison\n\n| Feature | Serverless Framework | AWS SAM | AWS Chalice |\n|---------|---------------------|---------|-------------|\n| Ease of use | Medium | Medium | High |\n| Multi-cloud | Yes | No | No |\n| Local testing | Yes (offline) | Yes (local) | Yes (local) |\n| Plugin ecosystem | Extensive | Limited | Minimal |\n| AWS-native | No | Yes | Yes |\n| Infrastructure as Code | CloudFormation | CloudFormation | CloudFormation |\n| Best for | Complex setups | AWS-native | Python APIs |\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":17263,"content_sha256":"64158df72bf0406cfd67e1d893163e7d3e99404189dc48b812666be7bbdd55db"},{"filename":"references/testing-lambda.md","content":"# Testing Python Lambda Functions\n\nTesting strategies for Python Lambda functions including unit tests, integration tests, and local emulation.\n\n## Testing Tools\n\n```txt\n# requirements-dev.txt\npytest>=8.0.0\npytest-cov>=5.0.0\npytest-asyncio>=0.23.0\nmoto>=5.0.0 # AWS service mocking - uses mock_aws decorator\nresponses>=0.25.0 # HTTP mocking\nfactory-boy>=3.3.0 # Test data generation\nfreezegun>=1.5.0 # Time mocking\n```\n\n## Unit Testing\n\n### Basic Test Structure\n\n```python\n# tests/test_lambda_function.py\nimport json\nimport pytest\nfrom unittest.mock import Mock, patch, MagicMock\n\nfrom lambda_function import lambda_handler, get_user, create_user\n\nclass TestLambdaHandler:\n \"\"\"Test suite for Lambda handler.\"\"\"\n\n @pytest.fixture\n def lambda_context(self):\n \"\"\"Create a mock Lambda context.\"\"\"\n context = Mock()\n context.function_name = 'test-function'\n context.memory_limit_in_mb = 256\n context.invoked_function_arn = 'arn:aws:lambda:us-east-1:123456789:function:test-function'\n context.aws_request_id = 'test-request-id'\n context.get_remaining_time_in_millis.return_value = 5000\n return context\n\n @pytest.fixture\n def api_gateway_event(self):\n \"\"\"Create a sample API Gateway event.\"\"\"\n return {\n 'httpMethod': 'GET',\n 'path': '/users/123',\n 'pathParameters': {'user_id': '123'},\n 'queryStringParameters': None,\n 'headers': {'Content-Type': 'application/json'},\n 'body': None,\n 'requestContext': {\n 'requestId': 'test-request-id',\n 'identity': {'sourceIp': '127.0.0.1'}\n }\n }\n\n def test_lambda_handler_get_user(self, api_gateway_event, lambda_context):\n \"\"\"Test GET /users/{id} endpoint.\"\"\"\n with patch('lambda_function.get_table') as mock_get_table:\n mock_table = Mock()\n mock_table.get_item.return_value = {'Item': {'id': '123', 'name': 'Test User'}}\n mock_get_table.return_value = mock_table\n\n response = lambda_handler(api_gateway_event, lambda_context)\n\n assert response['statusCode'] == 200\n body = json.loads(response['body'])\n assert body['id'] == '123'\n assert body['name'] == 'Test User'\n\n def test_lambda_handler_user_not_found(self, api_gateway_event, lambda_context):\n \"\"\"Test 404 response when user not found.\"\"\"\n with patch('lambda_function.get_table') as mock_get_table:\n mock_table = Mock()\n mock_table.get_item.return_value = {}\n mock_get_table.return_value = mock_table\n\n response = lambda_handler(api_gateway_event, lambda_context)\n\n assert response['statusCode'] == 404\n body = json.loads(response['body'])\n assert 'error' in body\n```\n\n### Testing with Fixtures\n\n```python\n# tests/conftest.py\nimport pytest\nimport json\nfrom unittest.mock import Mock\n\[email protected]\ndef mock_context():\n \"\"\"Standard mock Lambda context.\"\"\"\n context = Mock()\n context.function_name = 'test-function'\n context.memory_limit_in_mb = 256\n context.invoked_function_arn = 'arn:aws:lambda:us-east-1:123456789:function:test'\n context.aws_request_id = 'test-request-id'\n context.get_remaining_time_in_millis.return_value = 30000\n return context\n\[email protected]\ndef mock_api_event():\n \"\"\"Factory for API Gateway events.\"\"\"\n def _make_event(\n method='GET',\n path='/',\n path_params=None,\n query_params=None,\n body=None,\n headers=None\n ):\n event = {\n 'httpMethod': method,\n 'path': path,\n 'pathParameters': path_params or {},\n 'queryStringParameters': query_params or {},\n 'headers': headers or {'Content-Type': 'application/json'},\n 'body': json.dumps(body) if body else None,\n 'requestContext': {'requestId': 'test-id'}\n }\n return event\n return _make_event\n\[email protected]\ndef mock_dynamodb_item():\n \"\"\"Factory for DynamoDB items.\"\"\"\n def _make_item(user_id='123', name='Test', email='[email protected]'):\n return {\n 'id': user_id,\n 'name': name,\n 'email': email,\n 'created_at': '2024-01-01T00:00:00Z'\n }\n return _make_item\n```\n\n## Moto: AWS Service Mocking\n\n### DynamoDB Testing\n\n```python\n# tests/test_with_moto.py\nimport pytest\nimport boto3\nfrom moto import mock_aws\nimport json\n\nfrom lambda_function import lambda_handler\n\[email protected]\ndef dynamodb_table():\n \"\"\"Create mock DynamoDB table.\"\"\"\n with mock_aws():\n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n\n table = dynamodb.create_table(\n TableName='test-users',\n KeySchema=[{'AttributeName': 'id', 'KeyType': 'HASH'}],\n AttributeDefinitions=[{'AttributeName': 'id', 'AttributeType': 'S'}],\n BillingMode='PAY_PER_REQUEST'\n )\n table.wait_until_exists()\n\n # Seed with test data\n table.put_item(Item={'id': '123', 'name': 'Test User', 'email': '[email protected]'})\n\n yield table\n\ndef test_get_user_with_moto(dynamodb_table, mock_context):\n \"\"\"Test using mocked DynamoDB.\"\"\"\n from lambda_function import get_table\n\n # Override the table in lambda_function\n import lambda_function\n lambda_function._table = dynamodb_table\n\n event = {\n 'httpMethod': 'GET',\n 'path': '/users/123',\n 'pathParameters': {'user_id': '123'}\n }\n\n response = lambda_handler(event, mock_context)\n\n assert response['statusCode'] == 200\n body = json.loads(response['body'])\n assert body['name'] == 'Test User'\n\n@mock_aws\ndef test_create_user():\n \"\"\"Test using decorator style.\"\"\"\n # Setup\n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n table = dynamodb.create_table(\n TableName='test-users',\n KeySchema=[{'AttributeName': 'id', 'KeyType': 'HASH'}],\n AttributeDefinitions=[{'AttributeName': 'id', 'AttributeType': 'S'}],\n BillingMode='PAY_PER_REQUEST'\n )\n\n # Test\n from lambda_function import create_user\n import lambda_function\n lambda_function._table = table\n\n result = create_user({'id': '456', 'name': 'New User'})\n\n # Verify\n response = table.get_item(Key={'id': '456'})\n assert response['Item']['name'] == 'New User'\n```\n\n### S3 Testing\n\n```python\n# tests/test_s3_operations.py\nimport pytest\nimport boto3\nfrom moto import mock_aws\nimport json\n\n@mock_aws\ndef test_s3_upload_and_retrieve():\n \"\"\"Test S3 operations.\"\"\"\n # Setup\n s3 = boto3.client('s3', region_name='us-east-1')\n bucket_name = 'test-bucket'\n s3.create_bucket(Bucket=bucket_name)\n\n # Test upload\n s3.put_object(\n Bucket=bucket_name,\n Key='test-file.json',\n Body=json.dumps({'key': 'value'})\n )\n\n # Test retrieve\n response = s3.get_object(Bucket=bucket_name, Key='test-file.json')\n content = json.loads(response['Body'].read())\n\n assert content['key'] == 'value'\n\n@mock_aws\ndef test_lambda_s3_trigger():\n \"\"\"Test Lambda triggered by S3 event.\"\"\"\n from lambda_function import lambda_handler\n\n s3_event = {\n 'Records': [{\n 'eventVersion': '2.1',\n 'eventSource': 'aws:s3',\n 'awsRegion': 'us-east-1',\n 'eventName': 'ObjectCreated:Put',\n 's3': {\n 'bucket': {'name': 'test-bucket'},\n 'object': {'key': 'uploads/file.txt'}\n }\n }]\n }\n\n context = Mock()\n response = lambda_handler(s3_event, context)\n\n assert response['statusCode'] == 200\n```\n\n### SQS Testing\n\n```python\n# tests/test_sqs.py\nimport pytest\nimport boto3\nfrom moto import mock_aws\nimport json\n\n@mock_aws\ndef test_sqs_send_and_receive():\n \"\"\"Test SQS operations.\"\"\"\n sqs = boto3.client('sqs', region_name='us-east-1')\n\n # Create queue\n queue = sqs.create_queue(QueueName='test-queue')\n queue_url = queue['QueueUrl']\n\n # Send message\n sqs.send_message(\n QueueUrl=queue_url,\n MessageBody=json.dumps({'task': 'process_data'})\n )\n\n # Receive message\n messages = sqs.receive_message(QueueUrl=queue_url)\n body = json.loads(messages['Messages'][0]['Body'])\n\n assert body['task'] == 'process_data'\n```\n\n## Testing AWS Chalice\n\n### Chalice Test Client\n\n```python\n# tests/test_chalice_app.py\nimport pytest\nimport json\nfrom chalice.test import Client\nfrom moto import mock_aws\nimport boto3\n\nfrom app import app\n\[email protected]\ndef client():\n \"\"\"Create Chalice test client.\"\"\"\n with Client(app) as client:\n yield client\n\n@mock_aws\ndef test_index_endpoint(client):\n \"\"\"Test GET / endpoint.\"\"\"\n response = client.http.get('/')\n\n assert response.status_code == 200\n assert response.json_body == {'message': 'Hello from Chalice!'}\n\n@mock_aws\ndef test_create_user(client):\n \"\"\"Test POST /users endpoint.\"\"\"\n # Setup mock DynamoDB\n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\n table = dynamodb.create_table(\n TableName='users',\n KeySchema=[{'AttributeName': 'id', 'KeyType': 'HASH'}],\n AttributeDefinitions=[{'AttributeName': 'id', 'AttributeType': 'S'}],\n BillingMode='PAY_PER_REQUEST'\n )\n table.wait_until_exists()\n\n response = client.http.post(\n '/users',\n body=json.dumps({'id': '123', 'name': 'Test User'}),\n headers={'Content-Type': 'application/json'}\n )\n\n assert response.status_code == 201\n assert 'id' in response.json_body\n\ndef test_404_response(client):\n \"\"\"Test 404 handling.\"\"\"\n response = client.http.get('/nonexistent')\n\n assert response.status_code == 404\n```\n\n### Testing Chalice Events\n\n```python\n# tests/test_chalice_events.py\nimport pytest\nfrom chalice.test import Client\nfrom app import app\n\[email protected]\ndef client():\n with Client(app) as client:\n yield client\n\ndef test_s3_event_handler(client):\n \"\"\"Test S3 event handler.\"\"\"\n event = client.events.generate_s3_event(\n bucket='my-bucket',\n key='uploads/file.txt'\n )\n\n response = client.lambda_.invoke(\n 'handle_s3_upload',\n event\n )\n\n assert response.payload == {'status': 'processed'}\n\ndef test_scheduled_event(client):\n \"\"\"Test CloudWatch scheduled event.\"\"\"\n event = client.events.generate_cw_event(\n source='aws.events',\n detail_type='Scheduled Event'\n )\n\n response = client.lambda_.invoke('daily_report', event)\n\n assert response.payload['status'] == 'completed'\n\ndef test_sns_event(client):\n \"\"\"Test SNS event handler.\"\"\"\n event = client.events.generate_sns_event(\n message=json.dumps({'notification': 'test'}),\n subject='Test Subject'\n )\n\n response = client.lambda_.invoke('handle_sns_message', event)\n\n assert response.payload['status'] == 'processed'\n```\n\n## Local Testing\n\n### SAM Local\n\n```bash\n# Install SAM CLI\npip install aws-sam-cli\n\n# Build the application\nsam build\n\n# Start local API\nsam local start-api\n\n# Invoke function locally\nsam local invoke ApiFunction -e events/api-get.json\n\n# Invoke with environment variables\nsam local invoke ApiFunction \\\n -e events/api-get.json \\\n --env-vars env.json\n```\n\n### Serverless Offline\n\n```bash\n# Install plugin\nnpm install serverless-offline\n\n# Start offline server\nserverless offline\n\n# With specific port\nserverless offline --httpPort 3000\n\n# Invoke function\nserverless invoke local -f api -p event.json\n```\n\n### LocalStack\n\n```yaml\n# docker-compose.yml\nversion: '3.8'\nservices:\n localstack:\n image: localstack/localstack:latest\n ports:\n - \"4566:4566\"\n environment:\n - SERVICES=lambda,s3,dynamodb,apigateway,sqs\n - DEBUG=1\n - LAMBDA_EXECUTOR=docker\n volumes:\n - \"/var/run/docker.sock:/var/run/docker.sock\"\n```\n\n```python\n# tests/test_with_localstack.py\nimport pytest\nimport boto3\nimport requests\nimport json\n\nLOCALSTACK_ENDPOINT = 'http://localhost:4566'\n\[email protected](scope='module')\ndef aws_clients():\n \"\"\"Create AWS clients pointing to LocalStack.\"\"\"\n return {\n 'lambda': boto3.client(\n 'lambda',\n endpoint_url=LOCALSTACK_ENDPOINT,\n region_name='us-east-1',\n aws_access_key_id='test',\n aws_secret_access_key='test'\n ),\n 'dynamodb': boto3.resource(\n 'dynamodb',\n endpoint_url=LOCALSTACK_ENDPOINT,\n region_name='us-east-1',\n aws_access_key_id='test',\n aws_secret_access_key='test'\n ),\n 'apigateway': boto3.client(\n 'apigateway',\n endpoint_url=LOCALSTACK_ENDPOINT,\n region_name='us-east-1',\n aws_access_key_id='test',\n aws_secret_access_key='test'\n )\n }\n\ndef test_deploy_and_invoke(aws_clients):\n \"\"\"Deploy Lambda and invoke via API Gateway.\"\"\"\n # This would deploy the Lambda and test end-to-end\n pass\n```\n\n## Integration Testing\n\n### Full Stack Test\n\n```python\n# tests/integration/test_api_integration.py\nimport pytest\nimport requests\nimport os\n\n# Skip if no deployment\npytestmark = pytest.mark.skipif(\n not os.getenv('API_ENDPOINT'),\n reason='API_ENDPOINT not set'\n)\n\[email protected]\ndef api_endpoint():\n return os.getenv('API_ENDPOINT')\n\[email protected]\ndef api_key():\n return os.getenv('API_KEY')\n\ndef test_health_check(api_endpoint):\n \"\"\"Test health endpoint.\"\"\"\n response = requests.get(f\"{api_endpoint}/health\")\n assert response.status_code == 200\n assert response.json()['status'] == 'ok'\n\ndef test_create_and_get_user(api_endpoint, api_key):\n \"\"\"Test full CRUD flow.\"\"\"\n headers = {'X-Api-Key': api_key}\n\n # Create user\n create_response = requests.post(\n f\"{api_endpoint}/users\",\n json={'name': 'Integration Test', 'email': '[email protected]'},\n headers=headers\n )\n assert create_response.status_code == 201\n user_id = create_response.json()['id']\n\n # Get user\n get_response = requests.get(\n f\"{api_endpoint}/users/{user_id}\",\n headers=headers\n )\n assert get_response.status_code == 200\n assert get_response.json()['name'] == 'Integration Test'\n\n # Cleanup\n requests.delete(f\"{api_endpoint}/users/{user_id}\", headers=headers)\n```\n\n## Code Coverage\n\n```bash\n# Run tests with coverage\npytest --cov=lambda_function --cov-report=term-missing\n\n# Generate HTML report\npytest --cov=lambda_function --cov-report=html\n\n# Generate XML report for CI\npytest --cov=lambda_function --cov-report=xml\n\n# Fail if coverage below threshold\npytest --cov=lambda_function --cov-fail-under=80\n```\n\n### Coverage Configuration\n\n```ini\n# .coveragerc\n[run]\nsource = .\nomit =\n */tests/*\n */venv/*\n */.venv/*\n */__pycache__/*\n\n[report]\nexclude_lines =\n pragma: no cover\n def __repr__\n raise NotImplementedError\n if __name__ == .__main__.:\n pass\n```\n\n## Testing Best Practices\n\n1. **Use fixtures** - For common setup and teardown\n2. **Mock external services** - Use moto for AWS services\n3. **Test error paths** - Not just happy paths\n4. **Use parameterized tests** - For multiple test cases\n5. **Keep tests fast** - Unit tests should run in milliseconds\n6. **Test in isolation** - Each test should be independent\n7. **Use factories** - For test data generation\n8. **Clean up resources** - Even in tests\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":15435,"content_sha256":"67a7202db9fa95c59a85e8f378c5fb4d44da306f2a93773209875810cb57fe57"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"AWS Lambda Python Integration","type":"text"}]},{"type":"paragraph","content":[{"text":"Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Overview","type":"text"}]},{"type":"paragraph","content":[{"text":"AWS Lambda Python integration with two approaches: ","type":"text"},{"text":"AWS Chalice","type":"text","marks":[{"type":"strong"}]},{"text":" (full-featured framework) and ","type":"text"},{"text":"Raw Python","type":"text","marks":[{"type":"strong"}]},{"text":" (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Use","type":"text"}]},{"type":"paragraph","content":[{"text":"Use this skill when:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Creating new Lambda functions in Python","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Migrating existing Python applications to Lambda","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Optimizing cold start performance for Python Lambda","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Choosing between framework-based and minimal Python approaches","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Configuring API Gateway or ALB integration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Setting up deployment pipelines for Python Lambda","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Instructions","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Choose Your Approach","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Approach","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Cold Start","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Best For","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Complexity","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"AWS Chalice","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\u003c 200ms","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"REST APIs, rapid development, built-in routing","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Low","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Raw Python","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"\u003c 100ms","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Simple handlers, maximum control, minimal dependencies","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Low","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Project Structure","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"AWS Chalice Structure","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"my-chalice-app/\n├── app.py # Main application with routes\n├── requirements.txt # Dependencies\n├── .chalice/\n│ ├── config.json # Chalice configuration\n│ └── deploy/ # Deployment artifacts\n├── chalicelib/ # Additional modules\n│ ├── __init__.py\n│ └── services.py\n└── tests/\n └── test_app.py","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Raw Python Structure","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"my-lambda-function/\n├── lambda_function.py # Handler entry point\n├── requirements.txt # Dependencies\n├── template.yaml # SAM/CloudFormation template\n└── src/ # Additional modules\n ├── __init__.py\n ├── handlers.py\n └── utils.py","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Implementation Examples","type":"text"}]},{"type":"paragraph","content":[{"text":"See the ","type":"text"},{"text":"References","type":"text","marks":[{"type":"link","attrs":{"href":"#references","title":null}}]},{"text":" section for detailed implementation guides. Quick examples:","type":"text"}]},{"type":"paragraph","content":[{"text":"AWS Chalice:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"from chalice import Chalice\napp = Chalice(app_name='my-api')\n\[email protected]('/')\ndef index():\n return {'message': 'Hello from Chalice!'}","type":"text"}]},{"type":"paragraph","content":[{"text":"Raw Python:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"def lambda_handler(event, context):\n return {\n 'statusCode': 200,\n 'body': json.dumps({'message': 'Hello from Lambda!'})\n }","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Core Concepts","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Cold Start Optimization","type":"text"}]},{"type":"paragraph","content":[{"text":"Key strategies:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Initialize at module level","type":"text","marks":[{"type":"strong"}]},{"text":" - Persists across warm invocations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use lazy loading","type":"text","marks":[{"type":"strong"}]},{"text":" - Defer heavy imports until needed","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cache boto3 clients","type":"text","marks":[{"type":"strong"}]},{"text":" - Reuse connections between invocations","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"Raw Python Lambda","type":"text","marks":[{"type":"link","attrs":{"href":"references/raw-python-lambda.md#cold-start-optimization","title":null}}]},{"text":" for detailed patterns.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Connection Management","type":"text"}]},{"type":"paragraph","content":[{"text":"Create clients at module level and reuse:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"_dynamodb = None\n\ndef get_table():\n global _dynamodb\n if _dynamodb is None:\n _dynamodb = boto3.resource('dynamodb').Table('my-table')\n return _dynamodb","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Environment Configuration","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"class Config:\n TABLE_NAME = os.environ.get('TABLE_NAME')\n DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'\n\n @classmethod\n def validate(cls):\n if not cls.TABLE_NAME:\n raise ValueError(\"TABLE_NAME required\")","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Best Practices","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Memory and Timeout Configuration","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Memory","type":"text","marks":[{"type":"strong"}]},{"text":": Start with 256MB for simple handlers, 512MB for complex operations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Timeout","type":"text","marks":[{"type":"strong"}]},{"text":": Set based on expected processing time","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Simple handlers: 3-5 seconds","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"API with DB calls: 10-15 seconds","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data processing: 30-60 seconds","type":"text"}]}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Dependencies","type":"text"}]},{"type":"paragraph","content":[{"text":"Keep ","type":"text"},{"text":"requirements.txt","type":"text","marks":[{"type":"code_inline"}]},{"text":" minimal:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"txt"},"content":[{"text":"# Core AWS SDK - always needed\nboto3>=1.35.0\n\n# Only add what you need\nrequests>=2.32.0 # If calling external APIs\npydantic>=2.5.0 # If using data validation","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Error Handling","type":"text"}]},{"type":"paragraph","content":[{"text":"Return proper HTTP codes with request ID:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"def lambda_handler(event, context):\n try:\n result = process_event(event)\n return {'statusCode': 200, 'body': json.dumps(result)}\n except ValueError as e:\n return {'statusCode': 400, 'body': json.dumps({'error': str(e)})}\n except Exception as e:\n print(f\"Error: {str(e)}\") # Log to CloudWatch\n return {'statusCode': 500, 'body': json.dumps({'error': 'Internal error'})}","type":"text"}]},{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"Raw Python Lambda","type":"text","marks":[{"type":"link","attrs":{"href":"references/raw-python-lambda.md#error-handling","title":null}}]},{"text":" for structured error patterns.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Logging","type":"text"}]},{"type":"paragraph","content":[{"text":"Use structured logging for CloudWatch Insights:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"python"},"content":[{"text":"import logging, json\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n# Structured log\nlogger.info(json.dumps({\n 'eventType': 'REQUEST',\n 'requestId': context.aws_request_id,\n 'path': event.get('path')\n}))","type":"text"}]},{"type":"paragraph","content":[{"text":"See ","type":"text"},{"text":"Raw Python Lambda","type":"text","marks":[{"type":"link","attrs":{"href":"references/raw-python-lambda.md#logging","title":null}}]},{"text":" for advanced patterns.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Deployment Options","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Quick Start","type":"text"}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Validation Checkpoint:","type":"text","marks":[{"type":"strong"}]},{"text":" Always run ","type":"text"},{"text":"serverless print","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"sam validate","type":"text","marks":[{"type":"code_inline"}]},{"text":" before deploying to catch configuration errors early.","type":"text"}]}]},{"type":"paragraph","content":[{"text":"Serverless Framework:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"yaml"},"content":[{"text":"# serverless.yml\nservice: my-python-api\nprovider:\n name: aws\n runtime: python3.12 # or python3.11\nfunctions:\n api:\n handler: lambda_function.lambda_handler\n events:\n - http:\n path: /{proxy+}\n method: ANY","type":"text"}]},{"type":"paragraph","content":[{"text":"AWS SAM:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"yaml"},"content":[{"text":"# template.yaml\nAWSTemplateFormatVersion: '2010-09-09'\nTransform: AWS::Serverless-2016-10-31\n\nResources:\n ApiFunction:\n Type: AWS::Serverless::Function\n Properties:\n CodeUri: ./\n Handler: lambda_function.lambda_handler\n Runtime: python3.12 # or python3.11\n Events:\n ApiEvent:\n Type: Api\n Properties:\n Path: /{proxy+}\n Method: ANY","type":"text"}]},{"type":"paragraph","content":[{"text":"AWS Chalice:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"chalice new-project my-api\ncd my-api\nchalice local 8080 # Test locally before deploying\nchalice deploy --stage dev","type":"text"}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Validation Checkpoint:","type":"text","marks":[{"type":"strong"}]},{"text":" Test locally with ","type":"text"},{"text":"chalice local","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"sam local invoke","type":"text","marks":[{"type":"code_inline"}]},{"text":" before deploying to production.","type":"text"}]}]},{"type":"paragraph","content":[{"text":"For complete deployment configurations including CI/CD, environment-specific settings, and advanced SAM/Serverless patterns, see ","type":"text"},{"text":"Serverless Deployment","type":"text","marks":[{"type":"link","attrs":{"href":"references/serverless-deployment.md","title":null}}]},{"text":".","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Constraints and Warnings","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Lambda Limits","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deployment package","type":"text","marks":[{"type":"strong"}]},{"text":": 250MB unzipped maximum (50MB zipped)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Memory","type":"text","marks":[{"type":"strong"}]},{"text":": 128MB to 10GB","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Timeout","type":"text","marks":[{"type":"strong"}]},{"text":": 15 minutes maximum","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Concurrent executions","type":"text","marks":[{"type":"strong"}]},{"text":": 1000 default (adjustable)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Environment variables","type":"text","marks":[{"type":"strong"}]},{"text":": 4KB total size","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Python-Specific Considerations","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cold start","type":"text","marks":[{"type":"strong"}]},{"text":": Python has excellent cold start performance; avoid heavy imports at module level","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Dependencies","type":"text","marks":[{"type":"strong"}]},{"text":": Keep ","type":"text"},{"text":"requirements.txt","type":"text","marks":[{"type":"code_inline"}]},{"text":" minimal; use Lambda Layers for shared dependencies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Native dependencies","type":"text","marks":[{"type":"strong"}]},{"text":": Must be compiled for Amazon Linux 2 (x86_64 or arm64)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Common Pitfalls","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Importing heavy libraries at module level","type":"text","marks":[{"type":"strong"}]},{"text":" - Defer to function level if not always needed","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Not handling Lambda context","type":"text","marks":[{"type":"strong"}]},{"text":" - Use ","type":"text"},{"text":"context.get_remaining_time_in_millis()","type":"text","marks":[{"type":"code_inline"}]},{"text":" for timeout awareness","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Not validating input","type":"text","marks":[{"type":"strong"}]},{"text":" - Always validate and sanitize event data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Printing sensitive data","type":"text","marks":[{"type":"strong"}]},{"text":" - Be careful with logs and CloudWatch","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Error Recovery:","type":"text","marks":[{"type":"strong"}]},{"text":" If deployment fails, check CloudWatch logs for initialization errors and run ","type":"text"},{"text":"sam logs","type":"text","marks":[{"type":"code_inline"}]},{"text":" to diagnose issues.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Considerations","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never hardcode credentials; use IAM roles and environment variables","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Validate all input data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use least privilege IAM policies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Enable CloudTrail for audit logging","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"References","type":"text"}]},{"type":"paragraph","content":[{"text":"For detailed guidance on specific topics:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"AWS Chalice","type":"text","marks":[{"type":"link","attrs":{"href":"references/chalice-lambda.md","title":null}},{"type":"strong"}]},{"text":" - Complete Chalice setup, routing, middleware, deployment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Raw Python Lambda","type":"text","marks":[{"type":"link","attrs":{"href":"references/raw-python-lambda.md","title":null}},{"type":"strong"}]},{"text":" - Minimal handler patterns, module caching, packaging","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Serverless Deployment","type":"text","marks":[{"type":"link","attrs":{"href":"references/serverless-deployment.md","title":null}},{"type":"strong"}]},{"text":" - Serverless Framework, SAM, CI/CD pipelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Testing Lambda","type":"text","marks":[{"type":"link","attrs":{"href":"references/testing-lambda.md","title":null}},{"type":"strong"}]},{"text":" - pytest, moto, SAM Local, localstack","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Examples","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Example 1: Create an AWS Chalice REST API","type":"text"}]},{"type":"paragraph","content":[{"text":"Input:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Create a Python Lambda REST API using AWS Chalice for a todo application","type":"text"}]},{"type":"paragraph","content":[{"text":"Process:","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Initialize Chalice project with ","type":"text"},{"text":"chalice new-project","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Configure routes for CRUD operations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Set up DynamoDB integration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Configure deployment stages","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deploy with ","type":"text"},{"text":"chalice deploy","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"paragraph","content":[{"text":"Output:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complete Chalice project structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"REST API with CRUD endpoints","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"DynamoDB table configuration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deployment configuration","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Example 2: Optimize Cold Start for Raw Python","type":"text"}]},{"type":"paragraph","content":[{"text":"Input:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"My Python Lambda has slow cold start, how do I optimize it?","type":"text"}]},{"type":"paragraph","content":[{"text":"Process:","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Analyze imports and initialization code","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Move heavy imports inside functions (lazy loading)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Cache boto3 clients at module level","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Remove unnecessary dependencies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use provisioned concurrency if needed","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Output:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Refactored code with lazy loading","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Optimized cold start \u003c 100ms","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Dependency analysis","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Example 3: Deploy with GitHub Actions","type":"text"}]},{"type":"paragraph","content":[{"text":"Input:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Configure CI/CD for Python Lambda with SAM","type":"text"}]},{"type":"paragraph","content":[{"text":"Process:","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create GitHub Actions workflow","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Set up Python environment and dependencies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Run pytest with coverage","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Package with SAM","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deploy to dev/prod stages","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Output:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complete ","type":"text"},{"text":".github/workflows/deploy.yml","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Multi-stage pipeline","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Integrated test automation","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Version","type":"text"}]},{"type":"paragraph","content":[{"text":"Version: 1.0.0","type":"text"}]}]},"metadata":{"date":"2026-11-02","name":"aws-lambda-python-integration","author":"@skillopedia","source":{"stars":366,"repo_name":"developer-kit","origin_url":"https://github.com/giuseppe-trisciuoglio/developer-kit/blob/HEAD/plugins/developer-kit-python/skills/aws-lambda-python-integration/SKILL.md","repo_owner":"giuseppe-trisciuoglio","body_sha256":"a4613e4cd68f767fb0bcf233dcc7d2ddfc2be2196e676ef5713d843f2b28d97f","cluster_key":"724fcc7ade5fe2127428aaa622ce5974d7696e635f8676ec68e7ebb9e55612d3","clean_bundle":{"format":"clean-skill-bundle-v1","source":"giuseppe-trisciuoglio/developer-kit/plugins/developer-kit-python/skills/aws-lambda-python-integration/SKILL.md","text_bytes":63800,"source_commit":"fe73fb33a09ee6562eeec7415a3f9a3bcf795177","skills_sh_rank":5630,"attachment_count":4,"text_attachments":4,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"plugins/developer-kit-python/skills/aws-lambda-python-integration/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"devops-infrastructure","category_label":"DevOps"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"devops-infrastructure","import_tag":"skills-sh-top20k-2026-11","description":"Provides AWS Lambda integration patterns for Python with cold start optimization. Use when deploying Python functions to AWS Lambda, choosing between AWS Chalice and raw Python approaches, optimizing cold starts, configuring API Gateway or ALB integration, or implementing serverless Python applications. Triggers include \"create lambda python\", \"deploy python lambda\", \"chalice lambda aws\", \"python lambda cold start\", \"aws lambda python performance\", \"python serverless framework\".","allowed-tools":"Read, Write, Edit, Bash, Glob, Grep"}},"renderedAt":1793661273079}

AWS Lambda Python Integration Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture. Overview AWS Lambda Python integration with two approaches: AWS Chalice (full-featured framework) and Raw Python (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations. When to Use Use this skill when: - Creating new Lambda functions in Python - Migrating existing Python applications to Lambda - Optimizing cold start performance for Python Lambda - Choosing between framework-based and minimal Python ap…