Skip to content

Lambda Handler

Base class for creating strongly typed Lambda functions with serialization, logging, and metrics support.


LambdaHandler dataclass

LambdaHandler()

Bases: LoggingMixins, MetricsMixins, HandlerMixins, BaseExecutor[REQUEST, RESPONSE], Generic[REQUEST, RESPONSE]

Base class for creating strongly-typed AWS Lambda handlers.

Provides a foundation for Lambda functions with built-in support for: - Request/response serialization and deserialization - Structured logging via AWS Lambda Powertools - CloudWatch metrics collection - SQS batch processing - DynamoDB Streams processing

Inherit from the LambdaHandler class to create a custom strongly typed lambda handler that expects a REQUEST object and returns a RESPONSE object that follow the ModelProtocol.

Class Type Parameters:

Name Bound or Constraints Description Default
REQUEST

The request model type (must implement ModelProtocol).

required
RESPONSE

The response model type (must implement ModelProtocol).

required
Example
@dataclass
class MyRequest(SchemaModel):
    name: str

@dataclass
class MyResponse(SchemaModel):
    message: str

class MyHandler(LambdaHandler[MyRequest, MyResponse]):
    def handle(self, request: MyRequest) -> MyResponse:
        return MyResponse(message=f"Hello, {request.name}!")

handler = MyHandler.get_handler()

deserialize_dynamodb_record classmethod

deserialize_dynamodb_record(record)

Parse a DynamoDB record into a request object.

This should be implemented if expected to process a dynamo DB record

Parameters:

Name Type Description Default
record DynamoDBRecord

A DynamoDB record generated from a DynamoDB Stream

required

Returns:

Type Description
REQUEST

Expected Request object

Source code in src/aibs_informatics_aws_lambda/common/handler.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
@classmethod
def deserialize_dynamodb_record(cls, record: DynamoDBRecord) -> REQUEST:
    """Parse a DynamoDB record into a request object.

    This should be implemented if expected to process a dynamo DB record

    Args:
        record (DynamoDBRecord): A DynamoDB record generated from a DynamoDB Stream

    Returns:
        Expected Request object
    """
    raise NotImplementedError(  # pragma: no cover
        "You must implement this method if processing dynamoDB stream events"
    )

deserialize_sqs_record classmethod

deserialize_sqs_record(record)

Deserialize an SQS Record into the Request object of this handler

By default, the "body" of the SQS record is deserialized using the class default deserialize_request method.

Parameters:

Name Type Description Default
record SQSRecord

An SQS record

required

Returns:

Type Description
REQUEST

The expected Request object for this handler class

Source code in src/aibs_informatics_aws_lambda/common/handler.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
@classmethod
def deserialize_sqs_record(cls, record: SQSRecord) -> REQUEST:
    """Deserialize an SQS Record into the Request object of this handler

    By default, the "body" of the SQS record is deserialized using
    the class default `deserialize_request` method.

    Args:
        record (SQSRecord): An SQS record

    Returns:
        The expected Request object for this handler class
    """
    return cls.deserialize_request(json.loads(record["body"]))

get_dynamodb_stream_handler classmethod

get_dynamodb_stream_handler(*args, **kwargs)

Create a handler for processing DynamoDB Stream events.

Creates a Lambda handler that processes batches of DynamoDB Stream records with partial failure support.

See Also

https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/

Parameters:

Name Type Description Default
*args

Positional arguments passed to the handler constructor.

()
**kwargs

Keyword arguments passed to the handler constructor.

{}

Returns:

Type Description
LambdaHandlerType

A callable Lambda handler function for DynamoDB Streams.

Example
handler = MyHandler.get_dynamodb_stream_handler()
Source code in src/aibs_informatics_aws_lambda/common/handler.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
@classmethod
def get_dynamodb_stream_handler(cls, *args, **kwargs) -> LambdaHandlerType:
    """Create a handler for processing DynamoDB Stream events.

    Creates a Lambda handler that processes batches of DynamoDB Stream
    records with partial failure support.

    See Also:
        https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/

    Args:
        *args: Positional arguments passed to the handler constructor.
        **kwargs: Keyword arguments passed to the handler constructor.

    Returns:
        A callable Lambda handler function for DynamoDB Streams.

    Example:
        ```python
        handler = MyHandler.get_dynamodb_stream_handler()
        ```
    """
    processor = BatchProcessor(event_type=EventType.DynamoDBStreams)
    logger = cls.get_logger(cls.service_name())

    # Create a record handler for each record in batch.
    def record_handler(record: DynamoDBRecord) -> Optional[JSON]:
        if not cls.should_process_dynamodb_record(record):
            logger.info(f"DynamoDB record {record} will not be processed.")
            return None
        lambda_handler = cls(*args, **kwargs)  # type: ignore[call-arg]
        lambda_handler.log = logger
        lambda_handler.add_logger_to_root()

        request = lambda_handler.deserialize_dynamodb_record(record)
        response = lambda_handler.handle(request=request)
        if response:
            lambda_handler.log.info("Sending Response")
            return lambda_handler.serialize_response(response)
        lambda_handler.log.info("Not sending Response")
        return None

    # Now create top-level handler
    @logger.inject_lambda_context(log_event=True)
    @batch_processor(record_handler=record_handler, processor=processor)  # type: ignore
    def handler(event, context: LambdaContext):
        return processor.response()

    return handler  # type: ignore

get_handler classmethod

get_handler(*args, **kwargs)

Create a Lambda handler function for this handler class.

Creates a wrapped handler function that: - Injects Lambda context for logging - Instantiates the handler class - Deserializes the incoming event - Invokes the handle method - Serializes and returns the response

Parameters:

Name Type Description Default
*args

Positional arguments passed to the handler constructor.

()
**kwargs

Keyword arguments passed to the handler constructor.

{}

Returns:

Type Description
LambdaHandlerType

A callable Lambda handler function suitable for AWS Lambda.

Example
# In your Lambda module
handler = MyHandler.get_handler()
Source code in src/aibs_informatics_aws_lambda/common/handler.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
@classmethod
def get_handler(cls, *args, **kwargs) -> LambdaHandlerType:
    """Create a Lambda handler function for this handler class.

    Creates a wrapped handler function that:
    - Injects Lambda context for logging
    - Instantiates the handler class
    - Deserializes the incoming event
    - Invokes the handle method
    - Serializes and returns the response

    Args:
        *args: Positional arguments passed to the handler constructor.
        **kwargs: Keyword arguments passed to the handler constructor.

    Returns:
        A callable Lambda handler function suitable for AWS Lambda.

    Example:
        ```python
        # In your Lambda module
        handler = MyHandler.get_handler()
        ```
    """

    logger = cls.get_logger(service=cls.service_name(), add_to_root=False)

    @logger.inject_lambda_context(log_event=True)
    def handler(event: LambdaEvent, context: LambdaContext) -> Optional[JSON]:
        lambda_handler = cls(*args, **kwargs)  # type: ignore[call-arg]
        logger.info(f"Instantiated {lambda_handler}.")
        lambda_handler.log = logger
        lambda_handler.context = context
        lambda_handler.add_logger_to_root()

        lambda_handler.log.info(f"Deserializing event: {event}")

        request = lambda_handler.deserialize_request(event)

        lambda_handler.log.info("Event successfully deserialized. Calling handler...")
        response = lambda_handler.handle(request=request)

        lambda_handler.log.info(
            f"Handler completed and returned following response: {response}"
        )
        if response:
            lambda_handler.log.info("Serializing response")
            return lambda_handler.serialize_response(response)

        return None

    return handler

get_sqs_batch_handler classmethod

get_sqs_batch_handler(
    *args, queue_type="standard", **kwargs
)

Create a handler for processing SQS batch records.

Creates a Lambda handler that processes batches of SQS messages with partial failure support, allowing successful messages to be acknowledged even if some fail.

See Also

https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/

Parameters:

Name Type Description Default
*args

Positional arguments passed to the handler constructor.

()
queue_type Literal['standard', 'fifo']

The SQS queue type - "standard" or "fifo". Defaults to "standard".

'standard'
**kwargs

Keyword arguments passed to the handler constructor.

{}

Returns:

Type Description
LambdaHandlerType

A callable Lambda handler function for SQS batch processing.

Raises:

Type Description
RuntimeError

If an invalid queue_type is provided.

Example
handler = MyHandler.get_sqs_batch_handler(queue_type="fifo")
Source code in src/aibs_informatics_aws_lambda/common/handler.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
@classmethod
def get_sqs_batch_handler(
    cls, *args, queue_type: Literal["standard", "fifo"] = "standard", **kwargs
) -> LambdaHandlerType:
    """Create a handler for processing SQS batch records.

    Creates a Lambda handler that processes batches of SQS messages
    with partial failure support, allowing successful messages to be
    acknowledged even if some fail.

    See Also:
        https://docs.powertools.aws.dev/lambda/python/latest/utilities/batch/

    Args:
        *args: Positional arguments passed to the handler constructor.
        queue_type (Literal["standard", "fifo"]): The SQS queue type - "standard" or "fifo".
            Defaults to "standard".
        **kwargs: Keyword arguments passed to the handler constructor.

    Returns:
        A callable Lambda handler function for SQS batch processing.

    Raises:
        RuntimeError: If an invalid queue_type is provided.

    Example:
        ```python
        handler = MyHandler.get_sqs_batch_handler(queue_type="fifo")
        ```
    """
    if queue_type == "standard":
        processor = BatchProcessor(event_type=EventType.SQS)
    elif queue_type == "fifo":
        processor = SqsFifoPartialProcessor()
    else:
        raise RuntimeError(
            "An invalid SQS queue_type ({queue_type}) was provided to the "
            "get_sqs_batch_handler() method. Valid values include: "
            "[standard, fifo]"
        )
    logger = cls.get_logger(cls.service_name())

    # Create a record handler for each record in batch.
    def record_handler(record: SQSRecord) -> Optional[JSON]:
        if not cls.should_process_sqs_record(record):
            logger.info(f"SQS record {record} elected not to be processed.")
            return None
        lambda_handler = cls(*args, **kwargs)
        lambda_handler.log = logger
        lambda_handler.add_logger_to_root()

        request = lambda_handler.deserialize_sqs_record(record)
        response = lambda_handler.handle(request=request)
        if response:
            lambda_handler.log.info("Sending Response")
            return lambda_handler.serialize_response(response)
        lambda_handler.log.info("Not sending Response")
        return None

    # Now create top-level handler
    @logger.inject_lambda_context(log_event=True)
    def handler(event: dict, context: LambdaContext) -> PartialItemFailureResponse:
        return process_partial_response(
            event=event,
            record_handler=record_handler,
            processor=processor,
            context=context,
        )

    return cast(LambdaHandlerType, handler)

load_input__remote classmethod

load_input__remote(remote_path)

Load input data from a remote S3 location.

Parameters:

Name Type Description Default
remote_path S3URI

The S3 URI to download the input from.

required

Returns:

Type Description
JSON

The JSON content from the S3 object.

Source code in src/aibs_informatics_aws_lambda/common/handler.py
81
82
83
84
85
86
87
88
89
90
91
@classmethod
def load_input__remote(cls, remote_path: S3URI) -> JSON:
    """Load input data from a remote S3 location.

    Args:
        remote_path (S3URI): The S3 URI to download the input from.

    Returns:
        The JSON content from the S3 object.
    """
    return download_to_json_object(remote_path)

should_process_dynamodb_record classmethod

should_process_dynamodb_record(record)

Filter for whether to handle an DynamoDB record

This allows to filter all stream events based on
  1. The type of event (entry modification, insertion, deletion...)
  2. The content of the affected record.

Parameters:

Name Type Description Default
record DynamoDBRecord

A DynamoDB record generated from a DynamoDB Stream

required

Returns:

Type Description
bool

True if handler should process request

Source code in src/aibs_informatics_aws_lambda/common/handler.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
@classmethod
def should_process_dynamodb_record(cls, record: DynamoDBRecord) -> bool:
    """Filter for whether to handle an DynamoDB record

    This allows to filter all stream events based on:
        1. The type of event (entry modification, insertion, deletion...)
        2. The content of the affected record.

    Args:
        record (DynamoDBRecord): A DynamoDB record generated from a DynamoDB Stream

    Returns:
        True if handler should process request
    """
    return True

should_process_sqs_record classmethod

should_process_sqs_record(record)

Filter for whether to handle an SQS Record.

This is invoked prior to deserializing and handling that SQS message.

Parameters:

Name Type Description Default
record SQSRecord

An SQS record

required

Returns:

Type Description
bool

True if handler should process request

Source code in src/aibs_informatics_aws_lambda/common/handler.py
160
161
162
163
164
165
166
167
168
169
170
171
172
@classmethod
def should_process_sqs_record(cls, record: SQSRecord) -> bool:
    """Filter for whether to handle an SQS Record.

    This is invoked prior to deserializing and handling that SQS message.

    Args:
        record (SQSRecord): An SQS record

    Returns:
        True if handler should process request
    """
    return True

write_output__remote classmethod

write_output__remote(output, remote_path)

Write output data to a remote S3 location.

Parameters:

Name Type Description Default
output JSON

The JSON content to upload.

required
remote_path S3URI

The S3 URI to upload the output to.

required
Source code in src/aibs_informatics_aws_lambda/common/handler.py
 93
 94
 95
 96
 97
 98
 99
100
101
@classmethod
def write_output__remote(cls, output: JSON, remote_path: S3URI) -> None:
    """Write output data to a remote S3 location.

    Args:
        output (JSON): The JSON content to upload.
        remote_path (S3URI): The S3 URI to upload the output to.
    """
    return upload_json(output, remote_path)