SkilVaultSign inStart free

Catalogue / python-lambda-playbook

python-lambda-playbook

Older skill: source not recordedSignedBuilds Python AWS Lambda integrations with raw handlers or Chalice, validated HTTP and event adapters, reusable AWS clients, isolated testing, and reviewed release plans. Use when the user asks to "write a Lambda handler", "set up a Chalice app", "connect Lambda to API Gateway or SQS", "test a Lambd…
---
name: python-lambda-playbook
description: >-
  Builds Python AWS Lambda integrations with raw handlers or Chalice, validated HTTP and
  event adapters, reusable AWS clients, isolated testing, and reviewed release plans.
  Use when the user asks to "write a Lambda handler", "set up a Chalice app", "connect
  Lambda to API Gateway or SQS", "test a Lambda locally with moto", or "prepare a SAM or
  Serverless deployment". Do not use for reporting stub operations as completed,
  promising fixed latency, or contacting cloud services without authorization.
---

Establish the account, runtime, and implementation boundary

Inspect the installed Python runtime, dependencies, event source, actual API schema, authentication, and build/deployment configuration before writing code.

  • Raw Python suits small explicit adapters; Chalice suits decorator routing with

supported AWS integrations.

  • Chalice provides routing and configuration conveniences — it is not a

dependency-injection container unless the application supplies that composition.

  • Keep transport logic, services, and repositories separate.
  • A raw project may use lambda_function.py, application modules, requirements, tests,

event fixtures, and a SAM/Serverless definition. A Chalice project uses app.py, chalicelib, .chalice/config.json, generated deployment outputs, and tests.

  • Do not modify generated artifacts to hide invalid configuration.

The owner supplies verified installed packages, CLI tools, local dependency trees, and container images. Do not install, download, or execute remote code. A request for identified local writes or isolated tests confirms that exact scope; obtain explicit confirmation before additional changes, containers or servers, API calls, secret access, event subscriptions, schedules, queues, uploads, cloud configuration, deployments, version/alias promotion, or removal. State account, region, stage, targets, payload, and cost before any external work.

Use a validated raw HTTP adapter

Select the actual event contract. API Gateway REST proxy, HTTP API v2, and ALB are different; normalize method/path/query/header/body fields explicitly. ALB uses its own response requirements, including statusDescription and encoding information, and may use multi-value headers. Do not classify every Records event as S3; inspect eventSource before dispatching S3/SNS/SQS records.

This complete original REST-v1 example delegates all CRUD operations to an injected repository, handles base64 input correctly, validates DTO fields, uses an allowlisted route table, and exposes no full configuration. It is a tested application adapter, not a claim that a durable repository is bundled.

import base64
import json
import logging
import re
from dataclasses import dataclass

log = logging.getLogger(__name__)

class PublicFailure(Exception):
    def __init__(self, status, message):
        super().__init__(message)
        self.status, self.message = status, message

@dataclass(frozen=True)
class HttpInput:
    method: str
    path: str
    query: dict
    headers: dict
    data: dict | None

    @classmethod
    def from_event(cls, event):
        if not isinstance(event, dict) or not isinstance(event.get('httpMethod'), str):
            raise PublicFailure(400, 'Invalid REST proxy event')
        headers = {str(k).lower(): str(v) for k,v in (event.get('headers') or {}).items()}
        raw = event.get('body')
        data = None
        if raw is not None:
            try:
                if event.get('isBase64Encoded'):
                    raw = base64.b64decode(raw, validate=True).decode('utf-8')
                if not isinstance(raw, str) or len(raw.encode('utf-8')) > 16384:
                    raise ValueError('Body size invalid')
                data = json.loads(raw)
                if not isinstance(data, dict):
                    raise ValueError('JSON object required')
            except (ValueError, TypeError, UnicodeError):
                raise PublicFailure(400, 'Invalid JSON body') from None
        return cls(event['httpMethod'].upper(), event.get('path') or '/',
                   event.get('queryStringParameters') or {}, headers, data)

    def header(self, name, default=None):
        return self.headers.get(name.lower(), default)

    def parameter(self, name, default=None):
        return self.query.get(name, default)


def http_response(status, body=None, *, headers=None, text=False):
    return {'statusCode':status, 'isBase64Encoded':False,
            'headers':{'Content-Type':'text/plain' if text else 'application/json', **(headers or {})},
            'body':'' if status == 204 else (str(body) if text else json.dumps(body))}

def label_input(data):
    if not isinstance(data, dict) or not isinstance(data.get('label'), str):
        raise PublicFailure(400, 'Label is required')
    label = data['label'].strip()
    if not 1 <= len(label) <= 120:
        raise PublicFailure(400, 'Label length is invalid')
    return {'label':label}

def make_http_handler(repository, authorize):
    def handler(event, context):
        request_id = getattr(context, 'aws_request_id', None)
        try:
            request = HttpInput.from_event(event)
            if context is not None and context.get_remaining_time_in_millis() < 1000:
                raise PublicFailure(503, 'Insufficient processing time')
            # Must validate identity and owner scope; header presence is not authentication.
            authorize(request)
            match = re.fullmatch(r'/specimens/([A-Za-z0-9_-]+)', request.path)
            identifier = match.group(1) if match else None
            collection = request.path == '/specimens'
            if not collection and not match:
                raise PublicFailure(404, 'Route not found')
            if request.method == 'GET' and collection:
                try:
                    limit = int(request.parameter('limit', '20'))
                except (ValueError,TypeError):
                    raise PublicFailure(400, 'Invalid limit') from None
                if not 1 <= limit <= 100:
                    raise PublicFailure(400, 'Limit out of range')
                return http_response(200, repository.list(limit, request.parameter('cursor')))
            if request.method == 'GET':
                value = repository.find(identifier)
                if value is None: raise PublicFailure(404, 'Specimen missing')
                return http_response(200,value)
            if request.method == 'POST' and collection:
                return http_response(201,repository.create(label_input(request.data)))
            if request.method == 'PUT' and identifier:
                value = repository.update(identifier,label_input(request.data))
                if value is None: raise PublicFailure(404, 'Specimen missing')
                return http_response(200,value)
            if request.method == 'DELETE' and identifier:
                if not repository.delete(identifier): raise PublicFailure(404, 'Specimen missing')
                return http_response(204)
            raise PublicFailure(405, 'Method not allowed')
        except PublicFailure as failure:
            return http_response(failure.status,{'error':failure.message,'requestId':request_id})
        except Exception as failure:
            log.error(json.dumps({'event':'request_failure','requestId':request_id,
                                  'errorType':type(failure).__name__}))
            return http_response(500,{'error':'Internal failure','requestId':request_id})
    return handler

Compose the actual exported lambda_handler once with the verified repository and authorization implementation. A factory argument is not the Lambda entry signature; its returned function is. Do not set the handler path to a factory requiring application dependencies. Test the packaged composition, not just the pure factory.

JSON serialization needs a reviewed policy for DynamoDB Decimal values, timestamps, and binary values. Do not silently turn a precise numeric field into a misleading string or float. Safe public errors can include a request ID and approved validation details; raw exception text and traceback can reveal secrets and should not be returned.

Supply persistent AWS adapters and cursor contracts

Reuse an injected boto3 DynamoDB table/resource and clients. Validate table/bucket/queue configuration before creating clients; avoid a default resource name that might select the wrong environment. Create a resource lazily when optional and keep it at module scope after initialization. Import expensive optional modules only on the path that needs them. This moves latency rather than eliminating it; measure first-use behavior too.

A dedicated repository can use conditional writes and an explicit single-key pagination schema. The complete original implementation below is suitable only for a reviewed table with a string id key. Tenant-filtered access requires a different actual key/index design; do not expose a global Scan to an unauthorized user.

import base64
import json
import uuid

class DynamoSpecimens:
    def __init__(self, table):
        self.table = table
    @staticmethod
    def cursor_encode(key):
        return base64.urlsafe_b64encode(json.dumps(key,separators=(',',':')).encode()).decode() if key else None
    @staticmethod
    def cursor_decode(text):
        if not text: return None
        try:
            value = json.loads(base64.b64decode(text, altchars=b'-_', validate=True))
        except (ValueError,TypeError):
            raise PublicFailure(400,'Invalid cursor') from None
        if not isinstance(value,dict) or set(value) != {'id'} or not isinstance(value['id'],str):
            raise PublicFailure(400,'Invalid cursor schema')
        return value
    def list(self, limit, cursor=None):
        arguments={'Limit':limit}
        key=self.cursor_decode(cursor)
        if key: arguments['ExclusiveStartKey']=key
        result=self.table.scan(**arguments)
        return {'items':result.get('Items',[]),
                'nextCursor':self.cursor_encode(result.get('LastEvaluatedKey'))}
    def find(self, identifier):
        return self.table.get_item(Key={'id':identifier},ConsistentRead=True).get('Item')
    def create(self, data):
        item={'id':uuid.uuid4().hex, **label_input(data)}
        self.table.put_item(Item=item,ConditionExpression='attribute_not_exists(id)')
        return item
    def update(self, identifier, data):
        try:
            result=self.table.update_item(Key={'id':identifier},
                UpdateExpression='SET #label = :label',
                ExpressionAttributeNames={'#label':'label'},
                ExpressionAttributeValues={':label':label_input(data)['label']},
                ConditionExpression='attribute_exists(id)',ReturnValues='ALL_NEW')
            return result['Attributes']
        except Exception as error:
            code=getattr(error,'response',{}).get('Error',{}).get('Code')
            if code=='ConditionalCheckFailedException': return None
            raise
    def delete(self, identifier):
        result=self.table.delete_item(Key={'id':identifier},ReturnValues='ALL_OLD')
        return bool(result.get('Attributes'))

A Scan Limit counts evaluated items, not necessarily returned matches; a cursor can exist even for an empty page. A composite/index key cursor must preserve its complete actual schema. Treat cursors as untrusted input and bind them to query/owner scope; encoding alone is not integrity protection. Prefer a Query against the correct tenant/index key over Scan where required.

Preview shortened. The full SKILL.md is in the pack.