

AWS SDK for Go V1 has reached end-of-support. We recommend that you migrate to [AWS SDK for Go V2](https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/). For additional details and information on how to migrate, please refer to this [announcement](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-go-v1-on-july-31-2025/).

# Amazon DynamoDB Examples Using the AWS SDK for Go
<a name="using-dynamodb-with-go-sdk"></a>

Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability. The AWS SDK for Go examples can integrate Amazon DynamoDB into your Go applications. The examples assume you have already set up and configured the SDK (that is, you have imported all required packages and set your credentials and region). For more information, see [Getting Started with the AWS SDK for Go](setting-up.md) and [Configuring the AWS SDK for Go](configuring-sdk.md).

The topic also provides a link to a downloadable version of DynamoDB, which includes an interactive web interface so you can experiment with DynamoDB offline.

You can download complete versions of these example files from the [aws-doc-sdk-examples](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/go/example_code/dynamodb) repository on GitHub.

**Topics**
+ [

# Listing all Amazon DynamoDB Tables
](dynamo-example-list-tables.md)
+ [

# Creating an Amazon DynamoDB Table
](dynamo-example-create-table.md)
+ [

# Creating an Amazon DynamoDB Table Item
](dynamo-example-create-table-item.md)
+ [

# Creating Amazon DynamoDB Table Items from a JSON File
](dynamo-example-load-table-items-from-json.md)
+ [

# Reading an Amazon DynamoDB Table Item
](dynamo-example-read-table-item.md)
+ [

# Getting Amazon DynamoDB Table Items Using Expression Builder
](dynamo-example-scan-table-item.md)
+ [

# Updating an Amazon DynamoDB Table Item
](dynamo-example-update-table-item.md)
+ [

# Deleting an Amazon DynamoDB Table Item
](dynamo-example-delete-table-item.md)

# Listing all Amazon DynamoDB Tables
<a name="dynamo-example-list-tables"></a>

The following example uses the DynamoDB [ListTables](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.ListTables) operation to list all of the tables in your default region.

Create the file *DynamoDBListTables.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
)
```

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` and create a new DynamoDB service client.

```
// 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)
```

Call **ListTables**. If an error occurs, print the error and exit. If no error occurs, loop through the tables, printing the name of each table.

```
// create the input configuration instance
input := &dynamodb.ListTablesInput{}

fmt.Printf("Tables:\n")

for {
    // Get the list of tables
    result, err := svc.ListTables(input)
    if err != nil {
        if aerr, ok := err.(awserr.Error); ok {
            switch aerr.Code() {
            case dynamodb.ErrCodeInternalServerError:
                fmt.Println(dynamodb.ErrCodeInternalServerError, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            // Print the error, cast err to awserr.Error to get the Code and
            // Message from an error.
            fmt.Println(err.Error())
        }
        return
    }

    for _, n := range result.TableNames {
        fmt.Println(*n)
    }

    // assign the last read tablename as the start for our next call to the ListTables function
    // the maximum number of table names returned in a call is 100 (default), which requires us to make
    // multiple calls to the ListTables function to retrieve all table names
    input.ExclusiveStartTableName = result.LastEvaluatedTableName

    if result.LastEvaluatedTableName == nil {
        break
    }
}
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBListTables.go) on GitHub.

# Creating an Amazon DynamoDB Table
<a name="dynamo-example-create-table"></a>

The following example uses the DynamoDB [CreateTable](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.CreateTable) operation to create the table **Music** your default region.

Create the file *DynamoDBCreateTable.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
    "log"
)
```

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`, and create the DynamoDB client.

```
// 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)
```

Call **CreateTable**. If an error occurs, print the error and exit. If no error occurs, print an message that the table was created.

```
// Create table Movies
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),
}

_, err := svc.CreateTable(input)
if err != nil {
    log.Fatalf("Got error calling CreateTable: %s", err)
}

fmt.Println("Created the table", tableName)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBCreateTable.go) on GitHub.

# Creating an Amazon DynamoDB Table Item
<a name="dynamo-example-create-table-item"></a>

The following example uses the DynamoDB [PutItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.PutItem) operation to create the table item with the `year` **2015** and `title` **The Big New Movie** in the `Movies` table in your default region.

Create the file *DynamoDBCreateItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
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/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

    "fmt"
    "log"
    "strconv"
)
```

Create the data structure we use to containing the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

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`, and create the DynamoDB client.

```
// 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 a struct with the movie data and marshall that data into a map of **AttributeValue** objects.

```
item := Item{
    Year:   2015,
    Title:  "The Big New Movie",
    Plot:   "Nothing happens at all.",
    Rating: 0.0,
}

av, err := dynamodbattribute.MarshalMap(item)
if err != nil {
    log.Fatalf("Got error marshalling new movie item: %s", err)
}
```

Create the input for **PutItem** and call it. If an error occurs, print the error and exit. If no error occurs, print an message that the item was added to the table.

```
// Create item in table Movies
tableName := "Movies"

input := &dynamodb.PutItemInput{
    Item:      av,
    TableName: aws.String(tableName),
}

_, err = svc.PutItem(input)
if err != nil {
    log.Fatalf("Got error calling PutItem: %s", err)
}

year := strconv.Itoa(item.Year)

fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBCreateItem.go) on GitHub.

# Creating Amazon DynamoDB Table Items from a JSON File
<a name="dynamo-example-load-table-items-from-json"></a>

The following example uses the DynamoDB [PutItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.PutItem) operation in a loop to create the items defined in *movie\$1data.json* file in the `Movies` table in your default region.

Create the file *DynamoDBLoadItems.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
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/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

    "encoding/json"
    "fmt"
    "log"
    "io/ioutil"
    "strconv"
)
```

Create the data structure we use to contain the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

Create a function to get the table items from the JSON file.

```
// Get table items from JSON file
func getItems() []Item {
    raw, err := ioutil.ReadFile("./.movie_data.json")
    if err != nil {
        log.Fatalf("Got error reading file: %s", err)
    }

    var items []Item
    json.Unmarshal(raw, &items)
    return items
}
```

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` and create a new DynamoDB service client.

```
// 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)
```

Call **getItems** to get the items. Loop through each item, marshall that data into a map of **AttributeValue** objects, add the item to the `Movies` table, and print out the title and year of the movie added to the table.

```
// Get table items from .movie_data.json
items := getItems()

// Add each item to Movies table:
tableName := "Movies"

for _, item := range items {
    av, err := dynamodbattribute.MarshalMap(item)
    if err != nil {
        log.Fatalf("Got error marshalling map: %s", err)
    }

    // Create item in table Movies
    input := &dynamodb.PutItemInput{
        Item:      av,
        TableName: aws.String(tableName),
    }

    _, err = svc.PutItem(input)
    if err != nil {
        log.Fatalf("Got error calling PutItem: %s", err)
    }

    year := strconv.Itoa(item.Year)

    fmt.Println("Successfully added '" + item.Title + "' (" + year + ") to table " + tableName)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBLoadItems.go) and a [sample JSON file](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/.movie_data.json) on GitHub.

# Reading an Amazon DynamoDB Table Item
<a name="dynamo-example-read-table-item"></a>

The following example uses the DynamoDB [GetItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.GetItem) operation to retrieve information about the item with the `year` **2015** and `title` **The Big New Movie** in the `movies` table in your default region.

Create the file *DynamoDBReadItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
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/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"

    "fmt"
    "log"
)
```

Create the data structure we use to contain the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

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` and create a new DynamoDB service client.

```
// 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)
```

Call **GetItem** to get the item from the table. If we encounter an error, print the error message. Otherwise, display information about the item.

```
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"

result, err := svc.GetItem(&dynamodb.GetItemInput{
    TableName: aws.String(tableName),
    Key: map[string]*dynamodb.AttributeValue{
        "Year": {
            N: aws.String(movieYear),
        },
        "Title": {
            S: aws.String(movieName),
        },
    },
})
if err != nil {
    log.Fatalf("Got error calling GetItem: %s", err)
}
```

If an item was returned, unmarshall the return value and display the year, title, plot, and rating.

```
if result.Item == nil {
    msg := "Could not find '" + *title + "'"
    return nil, errors.New(msg)
}
    
item := Item{}

err = dynamodbattribute.UnmarshalMap(result.Item, &item)
if err != nil {
    panic(fmt.Sprintf("Failed to unmarshal Record, %v", err))
}

fmt.Println("Found item:")
fmt.Println("Year:  ", item.Year)
fmt.Println("Title: ", item.Title)
fmt.Println("Plot:  ", item.Plot)
fmt.Println("Rating:", item.Rating)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBReadItem.go) on GitHub.

# Getting Amazon DynamoDB Table Items Using Expression Builder
<a name="dynamo-example-scan-table-item"></a>

The following example uses the DynamoDB [Scan](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.Scan) operation to get items with a `rating` greater than **4.0** in the `year` **2013** in the `Movies` table in your default region.

The example uses the [Expression Builder](https://aws.amazon.com/blogs/developer/introducing-amazon-dynamodb-expression-builder-in-the-aws-sdk-for-go/) package released in version 1.11.0 of the AWS SDK for Go in September 2017.

Create the file *DynamoDBScanItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
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/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
    "github.com/aws/aws-sdk-go/service/dynamodb/expression"

    "fmt"
    "log"
)
```

Create the data structure we use to contain the information about the table item.

```
// Create struct to hold info about new item
type Item struct {
    Year   int
    Title  string
    Plot   string
    Rating float64
}
```

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` and create a new DynamoDB service client.

```
// 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 variables for the minimum rating and year for the table items to retrieve.

```
tableName := "Movies"
minRating := 4.0
year := 2013
```

Create the expression defining the year for which we filter the table items to retrieve, and the projection so we get the title, year, and rating for each retrieved item. Then build the expression.

```
// Create the Expression to fill the input struct with.
// Get all movies in that year; we'll pull out those with a higher rating later
filt := expression.Name("Year").Equal(expression.Value(year))

// Or we could get by ratings and pull out those with the right year later
//    filt := expression.Name("info.rating").GreaterThan(expression.Value(min_rating))

// Get back the title, year, and rating
proj := expression.NamesList(expression.Name("Title"), expression.Name("Year"), expression.Name("Rating"))

expr, err := expression.NewBuilder().WithFilter(filt).WithProjection(proj).Build()
if err != nil {
    log.Fatalf("Got error building expression: %s", err)
}
```

Create the inputs for and call **Scan** to retrieve the items from the table (the movies made in 2013).

```
// Build the query input parameters
params := &dynamodb.ScanInput{
    ExpressionAttributeNames:  expr.Names(),
    ExpressionAttributeValues: expr.Values(),
    FilterExpression:          expr.Filter(),
    ProjectionExpression:      expr.Projection(),
    TableName:                 aws.String(tableName),
}

// Make the DynamoDB Query API call
result, err := svc.Scan(params)
if err != nil {
    log.Fatalf("Query API call failed: %s", err)
}
```

Loop through the movies from 2013 and display the title and rating for those where the rating is greater than 4.0

```
numItems := 0

for _, i := range result.Items {
    item := Item{}

    err = dynamodbattribute.UnmarshalMap(i, &item)

    if err != nil {
        log.Fatalf("Got error unmarshalling: %s", err)
    }

    // Which ones had a higher rating than minimum?
    if item.Rating > minRating {
        // Or it we had filtered by rating previously:
        //   if item.Year == year {
        numItems++

        fmt.Println("Title: ", item.Title)
        fmt.Println("Rating:", item.Rating)
        fmt.Println()
    }
}

fmt.Println("Found", numItems, "movie(s) with a rating above", minRating, "in", year)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBScanItems.go) on GitHub.

# Updating an Amazon DynamoDB Table Item
<a name="dynamo-example-update-table-item"></a>

The following example uses the DynamoDB [UpdateItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.UpdateItem) operation to update the rating to **0.5** for the item with the `year` **2015** and `title` **The Big New Movie** in the `Movies` table in your default region.

Create the file *DynamoDBUpdateItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
    "log"
)
```

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` and create a new DynamoDB service client.

```
// 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)
```

Call **UpdateItem** to add the item to the table. If we encounter an error, print the error message. Otherwise, display a message that the item was updated.

```
// Update item in table Movies
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"
movieRating := "0.5"

input := &dynamodb.UpdateItemInput{
    ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
        ":r": {
            N: aws.String(movieRating),
        },
    },
    TableName: aws.String(tableName),
    Key: map[string]*dynamodb.AttributeValue{
        "Year": {
            N: aws.String(movieYear),
        },
        "Title": {
            S: aws.String(movieName),
        },
    },
    ReturnValues:     aws.String("UPDATED_NEW"),
    UpdateExpression: aws.String("set Rating = :r"),
}

_, err := svc.UpdateItem(input)
if err != nil {
    log.Fatalf("Got error calling UpdateItem: %s", err)
}

fmt.Println("Successfully updated '" + movieName + "' (" + movieYear + ") rating to " + movieRating)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBUpdateItem.go) on GitHub.

# Deleting an Amazon DynamoDB Table Item
<a name="dynamo-example-delete-table-item"></a>

The following example uses the DynamoDB [DeleteItem](https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/#DynamoDB.DeleteItem) operation to delete the item with the `year` **2015** and `title` **The Big New Movie** from the `Movies` table in your default region.

Create the file *DynamoDBUpdateItem.go*. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

```
import (
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/dynamodb"

    "fmt"
    "log"
)
```

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` and create a new DynamoDB service client.

```
// 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)
```

Call **DeleteItem** to delete the item from the table. If we encounter an error, print the error message. Otherwise, display a message that the item was deleted.

```
tableName := "Movies"
movieName := "The Big New Movie"
movieYear := "2015"

input := &dynamodb.DeleteItemInput{
    Key: map[string]*dynamodb.AttributeValue{
        "Year": {
            N: aws.String(movieYear),
        },
        "Title": {
            S: aws.String(movieName),
        },
    },
    TableName: aws.String(tableName),
}

_, err := svc.DeleteItem(input)
if err != nil {
    log.Fatalf("Got error calling DeleteItem: %s", err)
}

fmt.Println("Deleted '" + movieName + "' (" + movieYear + ") from table " + tableName)
```

See the [complete example](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/go/example_code/dynamodb/DynamoDBDeleteItem.go) on GitHub.