Use Go Lambda and API Gateway to Generate DynamoDB Tables on Demand
Tags: lambda, dynamodb, apigateway, go
Published: 2023-09-10 20:48:54

In my previous [post](https://dev.to/aws-builders/creating-an-aws-lambda-function-in-go-and-troubleshooting-common-errors-2k6h), 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)
}

```
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](https://dev.to/aws-builders/creating-an-aws-lambda-function-in-go-and-troubleshooting-common-errors-2k6h)), let's test it to make sure that it's working as expected:
![Test Lambda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mi3lr9xcp7c316z9o68.png)

We're looking for the successful result:

![Success](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/myzf3ff8od137gi5zx0f.png)

_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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aemky3ofh9p17d670xoc.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yp8mvdpl28d3ha6g7h9m.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h816uc5uitth50g25o3x.png)

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

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

![Stage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6usr2a6grxfx9irgkzzv.png)

- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dg4mzzmvn7kuowlur3v5.png)

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!