Python serverless aws example

Carry 16 Published: 10/29/2024

Python serverless aws example

Here's an example of a Python-based AWS Lambda function that uses the Serverless framework to process API Gateway requests:

First, let's create a new directory for our project and install the necessary dependencies:

mkdir my-python-lambda

cd my-python-lambda

pip install serverless

Next, create a serverless.yml file in the root of your project with the following content:

service: my-python-lambda

provider:

name: aws

runtime: python3.8

region: us-west-2

functions:

my-function:

handler: lambda_handler

events:

http:

path: /

method: get

This serverless.yml file defines a single Lambda function named my-function that handles GET requests to the root URL (/) of your API Gateway.

Now, create a new Python file in the same directory called lambda_handler.py with the following content:

import boto3

dynamodb = boto3.resource('dynamodb')

table_name = 'my-table'

def lambda_handler(event, context):

Get the request parameter from the event

name = event.get('name')

Check if the name is provided in the request

if name:

Use the DynamoDB table to retrieve data for the given name

table = dynamodb.Table(table_name)

response = table.get_item(Key={'name': name})

Return the response as a JSON object

return {

'statusCode': 200,

'body': json.dumps(response['Item']) if response else json.dumps({'error': 'Name not found'})

}

else:

If no name is provided, return an error message

return {'statusCode': 400, 'body': json.dumps({'error': 'No name provided'})}

This Python function defines the Lambda handler for our my-function. It retrieves the request parameter name from the event object and uses it to retrieve data from a DynamoDB table named my-table. The response is returned as a JSON object.

To deploy this serverless application, run the following command:

serverless deploy

This will create a new AWS Lambda function and API Gateway with the configuration specified in your serverless.yml file. You can then test your API by sending GET requests to the root URL of your API Gateway.

For example, using the curl command:

curl -X GET http://your-api-gateway-url.com/

This should return a JSON object containing the data for the name specified in the request. If no name is provided, it will return an error message.

That's a basic example of how to use Python and AWS Lambda with Serverless framework!

Serverless Python example

I'd be happy to provide an example of a serverless Python application!

Serverless computing is a cloud-based architecture that allows you to write and deploy code without worrying about the underlying infrastructure. In this case, we'll use AWS Lambda, Amazon's serverless platform.

Here's an example of a simple Python function that handles API requests:

import boto3

import json

dynamodb = boto3.resource('dynamodb')

table_name = 'my-table'

def lambda_handler(event, context):

Get the request parameters from the event object

name = event['pathParameters']['name']

try:

table = dynamodb.Table(table_name)

response = table.get_item(Key={'name': name})

if response['Item']:

If the item exists in DynamoDB, return it

return {

'statusCode': 200,

'body': json.dumps(response['Item']),

'headers': {'Content-Type': 'application/json'}

}

else:

If the item doesn't exist, return a 404 error

return {

'statusCode': 404,

'body': 'The item was not found!',

'headers': {'Content-Type': 'application/json'}

}

except Exception as e:

Log any errors and return a 500 error

print(f'Error: {str(e)}')

return {

'statusCode': 500,

'body': 'An error occurred while processing your request.',

'headers': {'Content-Type': 'application/json'}

}

This code defines a Lambda function that:

Retrieves the request parameters from the event object. Checks if an item with the requested name exists in DynamoDB using a get_item call. If the item exists, returns it as JSON data. If the item doesn't exist, returns a 404 error message.

To deploy this Lambda function, follow these steps:

Create an AWS account and navigate to the AWS Management Console. Click on the 'Services' dropdown menu and select 'Lambda'. Click the 'Create function' button. Choose 'Author from scratch', then enter a name for your function (e.g., 'my-lambda') and set the runtime environment as 'Python 3.8'. In the 'Handler' field, enter 'lambda_handler', which is the name of the Python function in our example code. Upload your Python code to the Lambda function by clicking 'Upload a .ZIP file or select an S3 bucket'. Set the execution role to 'LambdaBasicExecutionRole', which is the default execution role for new Lambda functions.

Once deployed, you can test your Lambda function using the AWS CLI or API Gateway:

aws lambda invoke --function-name my-lambda --payload '{"pathParameters":{"name":"John"}}'

This command invokes the Lambda function with a JSON payload that includes a 'name' parameter. The Lambda function will return a response containing either the requested item or an error message, depending on whether the item exists in DynamoDB.

In this example, we've used AWS Lambda and DynamoDB to create a serverless application that handles API requests without requiring any upfront infrastructure provisioning. This architecture is ideal for applications that have varying levels of traffic, as you only pay for the compute time consumed by your code.