Deploy Python APIs to AWS Lambda In Minutes

joshflow

Joshua Tanke

Posted on September 27, 2024

Deploy Python APIs to AWS Lambda In Minutes

This short guide will show you how to deploy a Python API to AWS Lambda using LaunchFlow, an open source deployment tool for AWS & GCP.

Here’s what the final code will look like:

import launchflow as lf
import numpy as np

def handler(event, context):
    result = np.random.randint(0, 100)
    return {
        "statusCode": 200,
        "body": f"Result: {result}",
    }

api = lf.aws.LambdaService(
    name="my-lambda-api",
    handler=handler,
    runtime=lf.aws.lambda_service.PythonRuntime(
        requirements_txt_path="requirements.txt"
    ),
)
Enter fullscreen mode Exit fullscreen mode

You'll also be able to add other AWS services (i.e. RDS) to your API with little to no effort:

import launchflow as lf

rds = lf.aws.RDS(
    name="my-rds-cluster",
    publicly_accessible=False,
    engine_version=lf.aws.rds.RDSEngineVersion.POSTGRES16,
)

def handler(event, context):
    result = rds.query("SELECT 1")  # TODO: Add your SQL query here
    return {
        "statusCode": 200,
        "body": f"Query result: {result}",
    }

api = lf.aws.LambdaService(
    name="my-lambda-api",
    handler=handler,
    runtime=lf.aws.lambda_service.PythonRuntime(
        requirements_txt_path="requirements.txt"
    ),
)
Enter fullscreen mode Exit fullscreen mode

Let's get started!

Step 1: Install the LaunchFlow SDK + CLI

You can install LaunchFlow using pip:

pip install launchflow
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize your project directory

Create / navigate to a new project directory, the run:

lf init
Enter fullscreen mode Exit fullscreen mode

This will prompt you for things like your project name, where you want to store your deployment state, etc. I would recommend choosing the options shown below to get started quickly:

LaunchFlow CLI init command

Step 3: Create your API

NOTE: You will need local AWS credentials for this step

If you choose the same prompts as above, you should have an infra.py file that looks like this:

import launchflow as lf

api = lf.aws.LambdaService("my-lambda-api", handler="TODO") 
Enter fullscreen mode Exit fullscreen mode

You can now run lf create to spin up an empty Lambda API in a dedicated environment in your AWS account.

lf create
Enter fullscreen mode Exit fullscreen mode

This will first prompt you to create a new Environment in your AWS account (this is essentially just a VPC + role + s3 bucket):

LaunchFlow CLI create command

Once your environment is created, you'll see the AWS Lambda infrastructure that will be deployed to the environment:
LaunchFlow CLI create plan

Approve the plan and watch your API get created in a couple of minutes:

LaunchFlow CLI create approve

Step 4: Deploy your custom code

Now that we have everything set up on AWS, let's deploy a custom handler function that depends on the Numpy Python package.

Create a main.py file for the handler code:

import numpy

def handler(event, context):
    result = np.random.randint(0, 100)
    return {
        "statusCode": 200,
        "body": f"Random Number: {result}",
    }
Enter fullscreen mode Exit fullscreen mode

Add a requirements.txt with numpy added:

numpy
Enter fullscreen mode Exit fullscreen mode

Then update the LambdaService handler + runtime options in the infra.py file:

import launchflow as lf

api = lf.aws.LambdaService(
    name="my-lambda-api",
    handler="main.handler",
    runtime=lf.aws.lambda_service.PythonRuntime(
        requirements_txt_path="requirements.txt"
    ),
)
Enter fullscreen mode Exit fullscreen mode

Now simply run lf deploy to launch it to your Lambda function!

lf deploy
Enter fullscreen mode Exit fullscreen mode

If all goes well, you should see the url to access your API:
LaunchFlow CLI deploy command

That's it! You now have a production-grade API deployed to AWS Lambda.

Bonus: Add AWS services to your Lambda

LaunchFlow includes a high-level Python SDK for interacting with RDS, S3, SQS, and other AWS services at runtime. For example, here's how you would connect to a private Postgres databases hosted on RDS inside your lambda function:

import launchflow as lf

rds = lf.aws.RDS(
    name="my-rds-cluster",
    publicly_accessible=False,
    engine_version=lf.aws.rds.RDSEngineVersion.POSTGRES16,
)

def handler(event, context):
    result = rds.query("SELECT 1")  # TODO: Add your SQL query here
    return {
        "statusCode": 200,
        "body": f"Query result: {result}",
    }

api = lf.aws.LambdaService(
    name="my-lambda-api",
    handler=handler,
    runtime=lf.aws.lambda_service.PythonRuntime(
        requirements_txt_path="requirements.txt"
    ),
)
Enter fullscreen mode Exit fullscreen mode

Simply add launchflow[aws] to your requirements.txt, then run lf deploy to create the RDS database + deploy the Lambda API changes!

Notice that none of these code examples include networking, roles, or any other low-level configuration. The LaunchFlow client handles that for us, while still exposing the options we need to customize our deployment environment.

NOTE: You can plug in your own Terraform modules to customize the low-level environment configuration if needed.

I hope this helps save you from getting lost in the AWS sauce!

Happy to connect over email (josh@launchflow.com) or LinkedIn if you need any help trying out the code examples.

Happy Launching! 🚀

💖 💪 🙅 🚩
joshflow
Joshua Tanke

Posted on September 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related