Go by Example: DynamoDB Get Item
Retrieve a single item from an Amazon DynamoDB table using its primary key. This sample shows how to use `GetItem` and unmarshal the result back into a Go struct.
Code
package main
import (
"context"
"fmt"
"log"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
type User struct {
ID string `dynamodbav:"id"`
Name string `dynamodbav:"name"`
Email string `dynamodbav:"email"`
}
func main() {
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-east-1"))
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
client := dynamodb.NewFromConfig(cfg)
// Define the primary key of the item to retrieve
key, err := attributevalue.MarshalMap(map[string]string{
"id": "123",
})
if err != nil {
log.Fatalf("failed to marshal key, %v", err)
}
// Retrieve the item
result, err := client.GetItem(context.TODO(), &dynamodb.GetItemInput{
TableName: aws.String("Users"),
Key: key,
})
if err != nil {
log.Fatalf("failed to get item, %v", err)
}
if result.Item == nil {
fmt.Println("Item not found")
return
}
// Unmarshal the item into a struct
var user User
err = attributevalue.UnmarshalMap(result.Item, &user)
if err != nil {
log.Fatalf("failed to unmarshal item, %v", err)
}
fmt.Printf("Found user: %s (%s)\n", user.Name, user.Email)
}Explanation
Retrieving data from DynamoDB by its primary key is done using the GetItem operation. This is the most efficient way to access a single record, as it provides direct access without scanning the table. The AWS SDK for Go v2 requires you to provide the key as a map of attribute values, which identifies the unique item you want to fetch.
Once the item is retrieved, the SDK returns it as a map[string]types.AttributeValue. To work with this data in your Go application, you typically want to convert it back into a strongly-typed struct. The attributevalue.UnmarshalMap helper function performs this reverse transformation, mapping the DynamoDB attributes back to your struct fields based on the dynamodbav tags.
It is important to handle the case where the item does not exist. In DynamoDB, a successful GetItem request for a non-existent key does not return an error; instead, it returns a result with a nil Item field. Your code should explicitly check for this condition to avoid null pointer exceptions or logic errors.
- Key Construction: Use
attributevalue.MarshalMapto easily create the primary key map from a Go map or struct. - Nil Check: Always check if
result.Itemis nil to determine if the record was found. - Unmarshaling: Use
attributevalue.UnmarshalMapto decode the raw DynamoDB response into a usable Go struct.

