luckily, my favourite one! Python!
So let's get started!
Update the Lambda function to fetch and store data
The first step is to update the Lambda function that fetches data from an external website and stores it in a serverless database. Here is an example of the same function written in Python:
import boto3
import requests
dynamo = boto3.client('dynamodb')
def lambda_handler(event, context):
# Fetch data from external website
response = requests.get('https://example.com/data')
data = response.json()
# Store data in DynamoDB table
item = {
'id': {'S': data['id']},
'data': {'S': data['data']}
}
dynamo.put_item(TableName='your-table-name', Item=item)
return {
'statusCode': 200,
'body': json.dumps({'message': 'Data stored in DynamoDB'})
}
This example uses the boto3 package to interact with DynamoDB and the requests package to fetch data from an external website, similar to the previous example. Note that the function uses python json module to parse data instead of JSON.parse() function in node.js
Update the Lambda function to retrieve data
The next step is to update the Lambda function that retrieves data from the serverless database and makes it accessible through the API Gateway. Here is an example of the same function written in Python:
import boto3
import json
dynamo = boto3.client('dynamodb')
def lambda_handler(event, context):
# Retrieve data from DynamoDB table
data = dynamo.scan(TableName='your-table-name')
# Return data to user
return {
'statusCode': 200,
'body': json.dumps(data)
}
This function uses the boto3 package to interact with DynamoDB and returns the data to the user as a JSON string using json.dumps()
Re-Creating a Lambda Authorizer
A Lambda authorizer is a Lambda function that you build to authorize access to your API Gateway APIs using bearer token authentication, such as OAuth or JWT.
Here's an example of a simple Lambda authorizer function that can be used to authenticate a user using a bearer token. This function will use the Okta library to validate the token and return the appropriate policy allowing or denying access to the API Gateway endpoint.
import json
from okta.framework import OktaAuth
def lambda_handler(event, context):
auth = OktaAuth(event)
claims = auth.verify_token()
if claims:
auth_response = auth.get_auth_response(claims)
else:
auth_response = auth.get_auth_response(None, 'Unauthorized')
return auth_response
This example uses the okta library to validate the token passed in the Authorization header and return the appropriate policy allowing or denying access to the API Gateway endpoint.
Updating Terraform Configuration
For the terraform configuration to use the python function in the Lambda function resource the runtime attribute needs to be updated from nodejs14.x to python3.8. Additionally, in order to link the newly created Lambda authorizer function to the API Gateway, we need to update the authorization attribute of aws_api_gateway_method resource to CUSTOM and add authorizer_id to it pointing to our newly created Lambda function.
resource "aws_api_gateway_method" "example" {
rest_api_id = aws_api_gateway_rest_api.api_name.id
resource_id = aws_api_gateway_resource.example.id
http_method = "GET"
authorization = "CUSTOM"
authorizer_id = aws_lambda_authorizer.authorizer_lambda.id
request_parameters = {
"method.request.header.Authorization": true
}
integration {
type = "AWS_PROXY"
uri = aws_lambda_function.data_lambda.invoke_arn
http_method = "POST"
request_templates = {
"application/json" = "{\"statusCode\": 200}"
}
}
}
Even Re-Create a Hello World Lambda Function
To create a simple "Hello World" Lambda function, you can use the following code:
def lambda_handler(event, context):
message = 'Hello World!'
return {
'statusCode': 200,
'body': json.dumps(message)
}
This function returns a JSON object containing the message "Hello World!"
Verify the Deployment
To verify that everything is set up correctly, you can test the API Gateway endpoint using a tool like Postman and check the logs of all Lambda functions and the DynamoDB table to ensure that the data is being fetched and stored correctly, accessible when the user is logged in, and that the authorizer is properly handling token validation.
Additionally, you can test the "Hello World" lambda function by invoking it from the AWS Lambda console or by making a request to it via an API Gateway endpoint.
Wrap Up!
There you have it! You wanted it you got it, but by updating these Lambda functions and the Terraform configuration to use Python instead of Node.js, you can continue to use the same functionality as before but with a different programming language.
Despite updating the dependencies and language, the function code and dependencies together, remains ready for deployment with Terraform to create the same product demonstrating how modular we can make these websites!