DEV Community

Cover image for Use Go Lambda and API Gateway to Generate DynamoDB Tables on Demand
Tetiana Mostova for AWS Community Builders

Posted on

Use Go Lambda and API Gateway to Generate DynamoDB Tables on Demand

In my previous post, we focused on setting up Go correctly for Lambda development, zipping and uploading our function and troubleshooting issues like missing files. Now let's look at actually building our function.

Build GoLang Lambda Function

This code is a Go function that creates a DynamoDB table.

package main

import (
    "context"
    "log"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
)

func createDynamoDBTable(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

    // Create DynamoDB client
    svc := dynamodb.New(sess)

    // Define the table name, attribute definitions, key schema, and provisioned throughput
    tableName := "Movies"
    input := &dynamodb.CreateTableInput{
        AttributeDefinitions: []*dynamodb.AttributeDefinition{
            {
                AttributeName: aws.String("Year"),
                AttributeType: aws.String("N"),
            },
            {
                AttributeName: aws.String("Title"),
                AttributeType: aws.String("S"),
            },
        },
        KeySchema: []*dynamodb.KeySchemaElement{
            {
                AttributeName: aws.String("Year"),
                KeyType:       aws.String("HASH"),
            },
            {
                AttributeName: aws.String("Title"),
                KeyType:       aws.String("RANGE"),
            },
        },
        ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
            ReadCapacityUnits:  aws.Int64(10),
            WriteCapacityUnits: aws.Int64(10),
        },
        TableName: aws.String(tableName),
    }

    // Create the DynamoDB table
    _, err := svc.CreateTable(input)
    if err != nil {
        log.Fatalf("Got error calling CreateTable: %s", err)
        return events.APIGatewayProxyResponse{
            StatusCode: 500,
            Body:       "Error creating DynamoDB table",
        }, err
    }

    return events.APIGatewayProxyResponse{
        StatusCode: 200,
        Body:       "Created the table " + tableName,
    }, nil
}

func main() {
    lambda.Start(createDynamoDBTable)
}

Enter fullscreen mode Exit fullscreen mode

First we import Go packages to use DynamoDB and Lambda.

The func keyword declares our function. The ctx parameter provides "context" - extra information like time limits for the function. Ctx carries details such as the time left before the function shuts down automatically. It also contains data about the request and response between Lambda and API Gateway. You can think of ctx as getting the party location and time so you know when and where it's happening and be there on time at the right place.

Inside the function we use the AWS Go SDK to connect to DynamoDB. We call code from other packages using dot notation like aws.String.

Then we create a Movies table with Year and Title columns.
The imported packages are like toolkits that let us use DynamoDB and Lambda. We import them so our code can work with these AWS services.

The createDynamoDBTable function then uses the toolkits to connect to DynamoDB. It creates the table by calling the CreateTable method from the toolkit.

main() runs first when executed. It starts our table creation function.

Test our function

After we zipped and uploaded the function (see detailed steps here), let's test it to make sure that it's working as expected:
Test Lambda

We're looking for the successful result:

Success

Note: AWS may create resources for you to simulate the execution environment. If you'd like to invoke your Lambda function using API Gateway, please, remove DynamoDB table that was created in this step.
Delete table

Add API Gateway to invoke Lambda

  • Navigate to the API Gateway service and click on "Create API" to start creating a new API.

Choose "HTTP API" or "REST API" depending on your requirements. HTTP APIs are suitable for simpler use cases, and that's what we'll use.

  • Define Your API's integration and Routes

Choose our "Lambda Function" as the integration type. This is the function that will be invoked when this API endpoint is accessed.

Integration

Next we'll add a Route. Routes define how incoming requests are mapped to the associated API Gateway resources and integrations. Each route can have different configurations, including the integration target (e.g., a Lambda function), request/response transformations, and authorization settings.

Add POST Route

Our API Gateway will route POST /CreateDBTable requests to our Lambda function.

  • Let's choose default stage and proceed with creation process

Stage

  • Invoke API

In order to invoke our Lambda function through the API Gateway that we've configured with a POST route to /CreateDBTable, we can use a tool like curl or a similar HTTP client, or we can use a service like Postman. Here's how we can invoke our Lambda function using curl from the command line:

curl -X POST <base URL of our API Gateway stage> <the path to the POST route we've defined>

Curl

And voilà! We have successfully created a DynamoDB table by invoking a Lambda function with API Gateway!

Conclusion

Now you know how to build a Lambda function in Go that creates resources like DynamoDB tables. You also set up API Gateway to trigger it on demand.

You've got the skills to make serverless functions using AWS and connect them to various services. This opens up lots of possibilities to build powerful applications!

Happy coding!

Top comments (0)