Go RestAPI and DynamoDB with Post/Get/Put/Delete example code

Go with DynamoDB for Post: saving data

Here’s an example of a Go REST API that can handle a POST request to insert data into a DynamoDB table:

package main

import (
    "context"
    "encoding/json"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-lambda-go/lambda"
    "github.com/aws/aws-lambda-go/lambdacontext"
    "fmt"
)

type Item struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Create a new AWS session
    sess := session.Must(session.NewSession())

    // Create a new DynamoDB client
    db := dynamodb.New(sess)

    // Get the request body
    var item Item
    json.Unmarshal([]byte(request.Body), &item)
    if item.ID == "" || item.Name == "" || item.Email == "" {
        return events.APIGatewayProxyResponse{
            Body:       "Missing required fields",
            StatusCode: 400,
        }, nil
    }

    // Create a new DynamoDB PutItemInput
    input := &dynamodb.PutItemInput{
        TableName: aws.String("my-table"),
        Item: map[string]*dynamodb.AttributeValue{
            "id": {
                S: aws.String(item.ID),
            },
            "name": {
                S: aws.String(item.Name),
            },
            "email": {
                S: aws.String(item.Email),
            },
        },
    }

    // Put the item into the DynamoDB table
    _, err := db.PutItem(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       fmt.Sprintf("Failed to insert item into DynamoDB: %s", err),
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item inserted into DynamoDB"),
        StatusCode: 200,
    }, nil
}

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

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function unmarshals the request body into an Item struct, which includes id, name, email fields. The function also checks if any of the fields is missing, if any of the field is missing it returns a Bad Request error message.

Go RestAPI to PUT data to DynamoDB example code

Here’s an example of a Go REST API that can handle a PUT request to update data in a DynamoDB table:

package main

import (
    "context"
    "encoding/json"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/aws/aws-lambda-go/lambda"
    "fmt"
)

type Item struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Create a new AWS session
    sess := session.Must(session.NewSession())

    // Create a new DynamoDB client
    db := dynamodb.New(sess)

    // Get the request body
    var item Item
    json.Unmarshal([]byte(request.Body), &item)
    if item.ID == "" || item.Name == "" || item.Email == "" {
        return events.APIGatewayProxyResponse{
            Body:       "Missing required fields",
            StatusCode: 400,
        }, nil
    }

    // Create a new DynamoDB UpdateItemInput
    input := &dynamodb.UpdateItemInput{
        TableName: aws.String("my-table"),
        Key: map[string]*dynamodb.AttributeValue{
            "id": {
                S: aws.String(item.ID),
            },
        },
        ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
            ":name": {
                S: aws.String(item.Name),
            },
            ":email": {
                S: aws.String(item.Email),
            },
        },
        UpdateExpression: aws.String("SET name = :name, email = :email"),
        ReturnValues:     aws.String("UPDATED_NEW"),
    }

    // Update the item in the DynamoDB table
    _, err := db.UpdateItem(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       fmt.Sprintf("Failed to update item in DynamoDB: %s", err),
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item updated in DynamoDB"),
        StatusCode: 200,
    }, nil
}

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

In this example, the HandleRequest function is the entry point for the Lambda function, and it takes two parameters: a context.Context and an events.APIGatewayProxyRequest. The function unmarshals the request body into an Item struct, which includes id, name, email fields.

Go RestAPI to Get data from DynamoDB example code

Here is an example of a Go REST API that retrieves data from a DynamoDB table:

package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and region from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

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

    // Create Router
    router := mux.NewRouter()

    // Define API endpoint
    router.HandleFunc("/items/{id}", func(w http.ResponseWriter, r *http.Request) {
        // Get item ID from request parameters
        vars := mux.Vars(r)
        id := vars["id"]

        // Prepare the input for the GetItem function call
        input := &dynamodb.GetItemInput{
            TableName: aws.String("myTable"),
            Key: map[string]*dynamodb.AttributeValue{
                "id": {
                    S: aws.String(id),
                },
            },
        }

        // Call GetItem
        result, err := svc.GetItem(input)
        if err != nil {
            log.Println(err.Error())
            return
        }

        // Write response
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(result.String()))
    }).Methods("GET")

    // Start Server
    log.Fatal(http.ListenAndServe(":8000", router))
}

This example uses the Gorilla mux router to handle HTTP requests and the AWS SDK for Go to interact with DynamoDB. The code defines an API endpoint that can be accessed at the path “/items/{id}” and listens on port 8000. When a GET request is received at this endpoint, the code retrieves the item ID from the request parameters, prepares an input for the DynamoDB GetItem function, and calls the function to retrieve the item with the specified ID. The item’s contents are returned in the response.

Note: you need to set up your AWS credentials in the same way as you would for any other AWS SDK that you use.

You can also use the Amazon DynamoDB Document Client, an abstraction over the low-level DynamoDB client that simplifies working with data in DynamoDB. You can find more information on the AWS documentation website.

Go RestAPI to Delete data from DynamoDB example code

Here is an example of a Go REST API that deletes data from a DynamoDB table:

package main

import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"
    "github.com/gorilla/mux"
    "log"
    "net/http"
)

func main() {
    // Initialize a session that the SDK will use to load
    // credentials from the shared credentials file ~/.aws/credentials
    // and region from the shared configuration file ~/.aws/config.
    sess := session.Must(session.NewSessionWithOptions(session.Options{
        SharedConfigState: session.SharedConfigEnable,
    }))

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

    // Create Router
    router := mux.NewRouter()

    // Define API endpoint
    router.HandleFunc("/items/{id}", func(w http.ResponseWriter, r *http.Request) {
        // Get item ID from request parameters
        vars := mux.Vars(r)
        id := vars["id"]

        // Prepare the input for the DeleteItem function call
        input := &dynamodb.DeleteItemInput{
            TableName: aws.String("myTable"),
            Key: map[string]*dynamodb.AttributeValue{
                "id": {
                    S: aws.String(id),
                },
            },
        }

        // Call DeleteItem
        _, err := svc.DeleteItem(input)
        if err != nil {
            log.Println(err.Error())
            w.WriteHeader(http.StatusInternalServerError)
            return
        }

        // Return success status
        w.WriteHeader(http.StatusOK)
    }).Methods("DELETE")

    // Start Server
    log.Fatal(http.ListenAndServe(":8000", router))
}

This example uses the Gorilla mux router to handle HTTP requests and the AWS SDK for Go to interact with DynamoDB. The code defines an API endpoint that can be accessed at the path “/items/{id}” and listens on port 8000. When a DELETE request is received at this endpoint, the code retrieves the item ID from the request parameters, prepares an input for the DynamoDB DeleteItem function, and calls the function to delete the item with the specified ID. If the delete is successful, the code returns a 200 OK status, otherwise it returns a 500 Internal Server Error status.

Just like the previous example, you need to set up your AWS credentials in the same way as you would for any other AWS SDK that you use.

SpringBoot AWS DynamoDB example code

What is AWS DynamoDB

Amazon DynamoDB is a fully managed, cloud-based, NoSQL database service that provides fast and predictable performance with seamless scalability. DynamoDB is designed to handle very high scale and high performance workloads, making it a popular choice for mobile, web, gaming, ad tech, IoT, and many other applications.

Some key features of DynamoDB include:

Scalability: DynamoDB can scale to millions of requests per second with virtually unlimited capacity, making it a highly scalable and reliable database service.

Performance: DynamoDB is designed for low-latency and high-throughput access, with single-digit millisecond response times and the ability to support millions of requests per second.

Flexibility: DynamoDB supports various data types, including strings, numbers, and binary data, and allows you to store and retrieve data using simple API calls.

Security: DynamoDB provides multiple security features, including encryption at rest and in transit, IAM integration, and VPC endpoints, to help you secure your data.

Integration with other AWS services: DynamoDB can be easily integrated with other AWS services, such as Lambda and SNS, to build complex event-driven architectures.

Overall, DynamoDB is a highly scalable, high-performance NoSQL database service that is suitable for a wide range of applications.

AWS DynamoDB vs MongoDB

Amazon DynamoDB and MongoDB are both NoSQL database management systems (DBMS) that can be used to store and manage large amounts of data in a flexible and scalable manner. However, they have some key differences:

Cloud vs. self-hosted: DynamoDB is a fully managed, cloud-based NoSQL database service, while MongoDB is an open-source NoSQL database that you can install and run on your own servers or in the cloud.

Data model: DynamoDB uses a key-value data model, while MongoDB uses a document-oriented data model based on JSON-like documents.

Scalability: DynamoDB is designed to scale to millions of requests per second and handle virtually unlimited capacity, while MongoDB requires manual scaling and sharding to support high-throughput workloads.

Performance: DynamoDB is optimized for low-latency and high-throughput access, with single-digit millisecond response times, while MongoDB is generally faster for writes but slower for reads.

Integration with other services: DynamoDB can be easily integrated with other AWS services, while MongoDB can be integrated with a variety of services through its plug-in system.

Overall, DynamoDB and MongoDB are both powerful NoSQL database management systems, but they are designed to solve different types of data management problems. DynamoDB is a fully managed, cloud-based NoSQL database service optimized for scalability and performance, while MongoDB is an open-source NoSQL database that you can host yourself.

AWS DynamoDB commandline

You can use the AWS command-line interface (CLI) to manage Amazon DynamoDB from the command line. Here are some examples of common DynamoDB commands using the AWS CLI:

To list all of the tables in your AWS account:

aws dynamodb list-tables

To create a new DynamoDB table:

aws dynamodb create-table \
  --table-name my-table \
  --attribute-definitions \
    AttributeName=id,AttributeType=S \
  --key-schema \
    AttributeName=id,KeyType=HASH \
  --provisioned-throughput \
    ReadCapacityUnits=5,WriteCapacityUnits=5

To delete a DynamoDB table:

aws dynamodb delete-table --table-name my-table

To put an item into a DynamoDB table:

aws dynamodb put-item \
  --table-name my-table \
  --item '{"id":{"S":"123"},"name":{"S":"John"}}'

To get an item from a DynamoDB table:

aws dynamodb get-item \
  --table-name my-table \

SpringBoot AWS DynamoDB example code

Here is an example of how you can use Amazon DynamoDB with Spring Boot:

1. First, you will need to include the AWS SDK for Java in your project. You can do this by adding the following dependency to your pom.xml file:


  com.amazonaws
  aws-java-sdk-dynamodb
  2.15.0


Next, you will need to configure your AWS credentials. You can do this by adding the following properties to your application.properties file:

aws.accessKeyId= YOUR_ACCESS_KEY_ID
aws.secretKey= YOUR_SECRET_KEY

Alternatively, you can use the default credentials provider chain to allow the SDK to automatically discover your credentials.

3. Now, you can create a service class to interact with DynamoDB. Here is an example of a service that puts and gets an item from a DynamoDB table:

@Service
public class DynamoDBService {

  @Value("${aws.dynamodb.tableName}")
  private String tableName;

  private final AmazonDynamoDB dynamoDB;

  public DynamoDBService(AmazonDynamoDB dynamoDB) {
    this.dynamoDB = dynamoDB;
  }

  public void putItem(String id, String name) {
    Map item = new HashMap<>();
    item.put("id", new AttributeValue

How to use Spring Data DynamoDB example | Spring Boot

In tradition approach, implementing Data Access Layer makes lots of boilerplate code. Spring Data helps us improve our codes and reduce efforts for development and maintenance. It supports us the ways to write interface for repositories and custom finder methods, the implementation will be done automatically by Spring Framework. In this tutorial, we’re gonna look at how to use Spring Data DynamoDB with Spring Boot.

Related Posts:
Spring MongoOperations to access MongoDB
How to build SpringBoot MongoDb RestfulApi
How to use SpringData MongoRepository to interact with MongoDB

Continue reading “How to use Spring Data DynamoDB example | Spring Boot”