I’ve been learning how to mess with AWS Lamdba functions, API Gateways, and DynamoDB for a job I’ve been trying to apply for. Instead of just watching youtube videos I made a connection to something I already know, Roblox. Hopefully this tutorial isn’t super confusing. Why would you want to use this? If you want to share data between games that aren’t in the same universe, or if you just want a third party backup that isn’t datastore, it could be useful. I did it just to learn.
Roblox Module LUA Code
local HttpService = game:GetService("HttpService")
--Enter your API URL EXAMPLE: https://ABCDE.execute-api.us-east-2.amazonaws.com/prod/updateDB
local apiUrl =
local DynamoDB = {}
function DynamoDB.write(items)
local data = {
action="WRITE",
items = items
}
local jsonData = HttpService:JSONEncode(data)
local response = HttpService:PostAsync(apiUrl, jsonData, Enum.HttpContentType.ApplicationJson)
print(response)
end
function DynamoDB.read(userId)
local data = {
action="READ",
ID=userId
}
local jsonData = HttpService:JSONEncode(data)
local response = HttpService:PostAsync(apiUrl, jsonData, Enum.HttpContentType.ApplicationJson)
local data = HttpService:JSONDecode(response)
print(data["OrderDate"])
return data.data
end
return DynamoDB
Lamdba Function Python Code:
import json
import boto3
from decimal import Decimal
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Test')
def convert_decimal(d):
if isinstance(d, Decimal):
return float(d)
return d
def convert_item(item):
if isinstance(item, dict):
return {k: convert_item(v) for k, v in item.items()}
elif isinstance(item, list):
return [convert_item(x) for x in item]
else:
return convert_decimal(item)
def lambda_handler(event, context):
body = event.get('body', '{}') # Default to '{}' if 'body' key is missing
try:
parsed_body = json.loads(body)
except json.JSONDecodeError:
return {
'statusCode': 400,
'body': json.dumps('Invalid JSON in request body')
}
action = parsed_body.get('action', '').upper()
if action == "WRITE":
items = parsed_body.get('items')
if not items:
return {
'statusCode': 400,
'body': json.dumps('Missing items key in the request body')
}
for item in items:
table.put_item(Item=item)
return {
'statusCode': 200,
'body': json.dumps('Items written successfully')
}
elif action == "READ":
primaryKey = parsed_body.get('ID')
if not primaryKey:
return {
'statusCode': 400,
'body': json.dumps('Missing ID key in the request body for READ action')
}
key = {'ID': primaryKey}
response = table.get_item(Key=key)
item = response.get('Item')
if item:
item = convert_item(item)
return {
'statusCode': 200,
'body': json.dumps(item)
}
else:
return {
'statusCode': 404,
'body': json.dumps({'ID': primaryKey, 'message': 'Item not found'})
}
else:
return {
'statusCode': 400,
'body': json.dumps('Unknown action, please pass WRITE or READ for action.')
}
Example LUA call
local DynamoDB = require( game.ServerScriptService.DynamoDB)
-- Example usage
local info = {
{ID = "123", OrderID = "samsamsam1", OrderDate = "2024-07-01", OrderTotal = 200}
}
DynamoDB.write(info)
DynamoDB.read("123")
Steps:
Database Table Creation
- Log into AWS as root user.
- Click the search bar and type DynamoDB
- Click tables on the left hand bar
- Click create table
- Enter your table name, partition key [Remember table name]
(Partition key is a main key, so if you’re saving user data you might want to use their UserID) - Leave the sort key alone
- I left it with default settings and then created the table
Lambda Code Setup
- Log into AWS as root user.
- Click the search bar and type Lambda
- Click create function
- Enter whatever function name you want, just make sure you remember it later.
- Click the runtime dropdown and select python. My AWS Lambda function is in Python.
- I left the architecture as x86_64, and the execution role as “Create a new role with basic lambda permission”
- Go to the code source, and paste the code from box 1 in.
- On this line table = dynamodb.Table(‘Test’) change ‘Test’ to be whatever database name you decided on in Database Table Creation step 5
- Next go to the IAM console https://console.aws.amazon.com/iam/
- Click roles on the left side
- Under permission policies search AmazonDynamoDBFullAccess and add it, now your lambda function has access to write to your DynamoDB tables
Api Gateway Setup
- Log into AWS as root user.
- Click the search bar and type API Gateway
- Click Create API
- Click build under Http API
- Click the integrations dropdown and select Lambda
- Then in the bar with the magnifying glass, choose your lambda function
- You can leave the method as any and click next, make sure your lambda function is chosen under integration target
- You can leave the stage name as default and click deploy
- Then on the left hand side under API gateway, you can click something that looks like API: apiName…(abcde123)
- There you can find your link, which you will add to the lua script
local apiUrl = “https://ABCDE.execute-api.us-east-2.amazonaws.com/prod/updateDB”
Game implementation
- Create a module script inside serverscriptservice or wherever you want to put it
- Paste the module script code
- Be sure to turn on API calls in the game settings
- Create a regular script in serverscriptservice that calls it like this: local DynamoDB = require( game.ServerScriptService.DynamoDB)
- Test it by writing and then reading an entry like so (here my primary key name was ID):
local info = {
{ID = “123”, OrderID = “samsamsam1”, OrderDate = “2024-07-01”, OrderTotal = 200}
}
DynamoDB.write(info)
DynamoDB.read(“123”) --123 is the primary key