Skip to content

Python Lambda Functions

Filter this guidePick generator option values to hide sections that don't apply.

The Python Lambda Function generator provides the ability to add a lambda function to an existing python project.

This generator creates a new python lambda handler with AWS CDK or Terraform infrastructure setup. The generated backend uses AWS Lambda for serverless deployment, with optional type-safety using the Parser from AWS Lambda Powertools. It sets up AWS Lambda Powertools for observability, including logging, AWS X-Ray tracing and Cloudwatch Metrics.

You can generate a new Lambda Function in two ways:

  1. Install the Nx Console VSCode Plugin if you haven't already
  2. Open the Nx Console in VSCode
  3. Click Generate (UI) in the "Common Nx Commands" section
  4. Search for @aws/nx-plugin - py#lambda-function
  5. Fill in the required parameters
    • Click Generate
    ParameterTypeDefaultDescription
    project Requiredstring-The project to add the lambda function to
    name Requiredstring-The name of the function to add
    functionPath string-The path within the project source directory to add the function to
    event Any | AlbModel | APIGatewayProxyEventModel | ApiGatewayAuthorizerToken | ApiGatewayAuthorizerRequest | APIGatewayProxyEventV2Model | ApiGatewayAuthorizerRequestV2 | APIGatewayWebSocketMessageEventModel | APIGatewayWebSocketConnectEventModel | APIGatewayWebSocketDisconnectEventModel | BedrockAgentEventModel | CloudFormationCustomResourceCreateModel | CloudFormationCustomResourceUpdateModel | CloudFormationCustomResourceDeleteModel | CloudwatchLogsModel | DynamoDBStreamModel | EventBridgeModel | IoTCoreThingEvent | IoTCoreThingTypeEvent | IoTCoreThingTypeAssociationEvent | IoTCoreThingGroupEvent | IoTCoreAddOrRemoveFromThingGroupEvent | IoTCoreAddOrDeleteFromThingGroupEvent | KafkaMskEventModel | KafkaSelfManagedEventModel | KinesisDataStreamModel | KinesisFirehoseModel | KinesisFirehoseSqsModel | LambdaFunctionUrlModel | S3BatchOperationModel | S3EventNotificationEventBridgeModel | S3Model | S3ObjectLambdaEvent | S3SqsEventNotificationModel | SesModel | SnsModel | SqsModel | TransferFamilyAuthorizer | VpcLatticeModel | VpcLatticeV2ModelAnyOptional event source model to use for the lambda function
    infra lambda | nonelambdaThe type of infrastructure to deploy your Lambda function with.
    iac inherit | cdk | terraforminheritThe preferred IaC provider. By default this is inherited from your initial selection.
    preferInstallDependencies booleantrueWhether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.

    The generator will add the following files to your project:

    • Directory<module-name>
      • <lambda-function>.py Function implementation

    If the functionPath option is provided, the generater will add the necessary files to the specified path:

    • Directory<module-name>
      • Directory<custom-path>
        • <function-name>.py Function implementation

    Since this generator vends infrastructure as code based on your chosen iacProvider, it will create a project in packages/common which includes the relevant CDK constructs or Terraform modules.

    The common infrastructure as code project is structured as follows:

    • Directorypackages/common/constructs
      • Directorysrc
        • Directoryapp/ Constructs for infrastructure specific to a project/generator
        • Directorycore/ Generic constructs which are reused by constructs in app
        • index.ts Entry point exporting constructs from app
      • project.json Project build targets and configuration

    The generator creates infrastructure as code for deploying your function based on your selected iacProvider:

    The generator creates CDK constructs which can be used to deploy your function, which reside in the packages/common/constructs directory.

    The deployed function has the following architecture:

    Event Source(SNS, SQS, ...)LambdaCloudWatch(Logs, Metrics)X-Ray(Traces)

    The generator vends the function itself; you wire the event source up in your stack to invoke it (for example, an API Gateway integration, an EventBridge rule, an S3 notification or an SQS event source mapping).

    The main function implementation is in <function-name>.py. Here’s an example:

    import os
    from aws_lambda_powertools import Logger, Metrics, Tracer
    from aws_lambda_powertools.metrics import MetricUnit
    from aws_lambda_powertools.utilities.parser import event_parser
    from aws_lambda_powertools.utilities.parser.models import EventBridgeModel
    from aws_lambda_powertools.utilities.typing import LambdaContext
    os.environ["POWERTOOLS_METRICS_NAMESPACE"] = "Foo"
    os.environ["POWERTOOLS_SERVICE_NAME"] = "Foo"
    logger: Logger = Logger()
    metrics: Metrics = Metrics()
    tracer: Tracer = Tracer()
    @tracer.capture_lambda_handler
    @metrics.log_metrics
    @event_parser(model=EventBridgeModel)
    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    logger.info("Received event", extra={"event": event.model_dump() })
    metrics.add_metric(name="InvocationCount", unit=MetricUnit.Count, value=1)
    try:
    # TODO: Implement
    metrics.add_metric(name="SuccessCount", unit=MetricUnit.Count, value=1)
    # TODO: Implement success response if required
    except Exception as e:
    logger.exception(e)
    metrics.add_metric(name="ErrorCount", unit=MetricUnit.Count, value=1)
    # TODO: Implement error response if required

    The generator sets up several features automatically:

    1. AWS Lambda Powertools integration for observability
    2. Metrics collection
    3. Type-safety using @event_parser

    The generator configures structured logging using AWS Lambda Powertools.

    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    logger.info("Received event", extra={"event": event.model_dump()})

    The logger automatically includes:

    • Event requests
    • Lambda context information
    • Cold start indicators

    AWS X-Ray tracing is configured automatically. You can add custom subsegments to your traces:

    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    # Creates a new subsegment
    with tracer.provider.in_subsegment("function-subsegment"):
    # Your logic here
    return ....

    CloudWatch metrics are collected automatically for each request. You can add custom metrics:

    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    metrics.add_metric(name="NewMetric", unit=MetricUnit.Count, value=1)
    return ...

    Default metrics include:

    • Invocation counts
    • Success/failure counts
    • Cold start metrics
    event ≠ Any

    If you chose an event when generating your lambda function, your function is instrumented with @event_parser from AWS Lambda Powertools. For example:

    @event_parser(model=EventBridgeModel)
    def lambda_handler(event: EventBridgeModel, context: LambdaContext):
    event.detail_type # <- type-safe with IDE autocompletion

    This allows you to define data models using Pydantic, in a similar manner to working with Fast API.

    event = Any

    If you selected Any for your event, the @event_parser decorator is not applied and the handler receives an untyped event dict. Regenerate with a specific event if you want Pydantic validation and typed field access.

    The generator automatically configures Python bundling for Lambda deployment packages using uv:

    Terminal window
    pnpm nx bundle <project-name>

    This process uses:

    1. uv export to export your Python dependencies to a requirements.txt file
    2. uv pip install to install dependencies for the target platform (x86_64-manylinux_2_28) for Lambda deployment

    This generator creates CDK or Terraform infrastructure as code based on your selected iacProvider. You can use this to deploy your function.

    This generator creates a CDK construct for deploying your function in the common/constructs folder. You can use this in a CDK application:

    import { MyProjectMyFunction } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Add the function to your stack
    const fn = new MyProjectMyFunction(this, 'MyFunction');
    }
    }

    This sets up:

    1. AWS Lambda function
    2. CloudWatch log group
    3. X-Ray tracing configuration
    4. CloudWatch metrics namespace

    This function can then be used as a target for any lambda event source:

    The example below demonstrates the CDK code for invoking your lambda function on a schedule using EventBridge:

    import { Rule, Schedule } from 'aws-cdk-lib/aws-events';
    import { LambdaFunction } from 'aws-cdk-lib/aws-events-targets';
    import { MyProjectMyFunction } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Add the function to your stack
    const fn = new MyProjectMyFunction(this, 'MyFunction');
    // Add the function to an EventBridge scheduled rule
    const eventRule = new Rule(this, 'MyFunctionScheduleRule', {
    schedule: Schedule.cron({ minute: '15' }),
    targets: [new LambdaFunction(fn)],
    });
    }
    }