Search code examples
amazon-web-servicesaws-lambdaaws-cdk

how to use external python library in python lambda function with typescript cdk


I am starting with a cdk project (typescript), I want to understand how can I deploy a lambda function written in python having dependency on external library (request). Also I would like to know recommended practices/ folder structure when working with multiple lambdas in same or different stacks.


Solution

  • The @aws-cdk/aws-lambda-python-alpha module's PythonFunction construct will package your Lambda's dependencies. The module's docs on packaging say:

    If requirements.txt, Pipfile or poetry.lock exists at the entry path, the construct will handle installing all required modules in a Lambda compatible Docker container... Python bundles are only recreated and published when a file in a source directory has changed.

    Choose a file structure that works for your use case. The important thing is that the PythonFunction construct's entry prop must point to your Lambda's code:

    new PythonFunction(this, 'MyFunction', {
      entry: '/path/to/my/function', // required
      runtime: Runtime.PYTHON_3_8, // required
      index: 'my_index.py', // optional, defaults to 'index.py'
      handler: 'my_exported_func', // optional, defaults to 'handler'
    });