Site icon NexGismo

Create your first AWS Lambda with Python

AWS Lambda with Python

AWS Lambda is a serverless computing service at Amazon Web Services (AWS) that allows developers to run code without having to provision or manage servers. It is best suited for when you need to execute code in response to events such as changes to data in an Amazon S3 bucket, updates on a DynamoDB table, or HTTP requests through Amazon API Gateway. In this blog post we will walk-through how to use AWS Lambda with Python and include comprehensive examples and best practices.

AWS Lambda, therefore, is a service for serverless computing that automatically handles underlying infrastructure management tasks so that you can concentrate on coding. This implies that with Lambda you can run codes to respond to different events without worrying about setting up or managing servers.

Benefits of Using AWS Lambda

Scenarios Where Lambda is Beneficial


1. Getting Started with AWS Lambda

Before diving into the details, let’s set up our environment.

Prerequisites:

2. Setting Up AWS CLI

First, install the AWS CLI using pip

pip install awscli



Now Let’s configure the AWS CLI with your credentials

aws configure  



This will prompt you to ask for your AWS Access Key, Secret Key, region and output format. Make sure you have the necessary IAM permissions to create and manage Lambda functions.

3. Creating Your First Lambda Function in Python

Let’s create a simple lambda function which returns greeting message.

Step 1: Writing the Code

Create a Project folder

mkdir hello_world_lambda  
cd hello_world_lambda  


Now we have to create a a file with name lambda_function.py which will hold Lambda handler body

def lambda_handler(event, context):  
    return {  
        'statusCode': 200,  
        'body': 'Hello, AWS Lambda with Python!'  
    }  

Step 2: Creating the Lambda Function

Using either the AWS Management Console or AWS CLI, you can also create the lambda function. I am using AWS CLI.

Now let’s Zip our file, which is lambda_function.py.

zip function.zip lambda_function.py


Creating an IAM Role

In order to create the lambda function, we need an IAM role that has the required permissions. Create a role called lambda_basic_execution which uses the policy named AWSLambdaBasicExecutionRole. These steps can be followed within the AWS Management Console below.

  1. Go to the IAM Console.
  2. Click on “Roles” > “Create role”.
  3. Select “AWS service” and choose “Lambda”.
  4. Attach the policy named “AWSLambdaBasicExecutionRole”.
  5. Name the role lambda_basic_execution.

Now Creating the Lambda Function via AWS CLI

Now I am assuming that your AWS CLI is properly setup, SO let run the following command on terminal

aws lambda create-function --function-name HelloWorldFunction \  
--zip-file fileb://function.zip --handler lambda_function.lambda_handler \  
--runtime python3.8 --role arn:aws:iam::YOUR_ACCOUNT_ID:role/lambda_basic_execution  

Make sure that you are replacing YOUR_ACCOUNT_ID with your actual AWS account ID. With this command we will creates a Lambda function named HelloWorldFunction using Python 3.8 runtime.

After the initial creation of a Lambda function, you may need to update your function body based on the different requirement you can easily do that by making changes in lambda_function.py and again you need to zip your code and run the following command

aws lambda update-function-code --function-name HelloWorldFunction \  
--zip-file fileb://function.zip



aws lambda update-function-code command is used to update the function’s body.

4. Activation of Lambda Functions

A number of AWS services can be used to activate the AWS Lambda. The HTTP endpoint which will trigger our Lambda function will be created by using Amazon API Gateway.

Step 1: Create an API

  1. Go to the Amazon API Gateway console.
  2. Click on “Create API”.
  3. Choose “HTTP API” and click “Build”.

Step 2: Configure a Resource and Method

  1. Under “Routes”, click “Create”.
  2. For the route, enter /hello.
  3. Choose “GET” as the method.
  4. For the integration type, select “Lambda Function”.
  5. Click “Add Integration” and specify the function name (HelloWorldFunction).

Step 3: Deploy the API

  1. Click on “Deployments”.
  2. Click “Create” to create a new deployment.
  3. Choose a stage name (e.g., dev) and deploy.

You will get a URL to invoke the API. You can test this by opening your browser or through curl.

curl https://YOUR_API_ID.execute-api.YOUR_REGION.amazonaws.com/dev/hello



You should see the response: {“statusCode”: 200, “body”: “Hello, AWS Lambda with Python!”}

5. Logging and Monitoring

Amazon CloudWatch is at hand when it comes to logging and monitoring in regard to AWS Lambda.

AWS Lambda produces logs automatically that are accessible via CloudWatch console on demand. For every function invocation, a log stream is generated.

6. Best Practices

Security

Performance

Monitoring

Conclusion

AWS Lambda with Python gives you an incredibly powerful and scalable solution for serverless computing. Just follow this blog article’s steps to efficiently create, deploy, and manage Lambda functions. Always follow security, performance, and monitoring best practices to ensure smooth running of your applications.

Lambda is particularly great for event-driven architectures, real-time data processing, scalable backend services and automation. Leveraging Lambda will allow you to write code without thinking about the underlying infrastructure – a time-saving measure that reduces costs in the long run.

Happy coding!

References:

Exit mobile version