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.

Upload/Download file CSV/Excel using Amazon Lambda with Go example code

Write example code: AWS Lambda with Go upload file

Here’s an example of an AWS Lambda function written in Go that can handle a file upload:

package main

import (
    "context"
    "fmt"
    "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/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "io"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

    // Get the file from the request body
    file, header, err := request.GetFile("file")
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to get file from request body",
            StatusCode: 400,
        }, nil
    }
    defer file.Close()

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(header.Filename),
        Body:   file,
    }

    // Upload the file to S3
    _, err = svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s uploaded to S3", header.Filename),
        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 retrieves the file from the request body by calling request.GetFile(“file”), which returns the file, its header, and any error that may have occurred. If there is an error, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to S3.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message about the uploaded file.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Write example code: AWS Lambda with Go download file

Here’s an example of an AWS Lambda function written in Go that can handle a file download from an S3 bucket:

package main

import (
    "context"
    "fmt"
    "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/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "io"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the request query parameters
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query parameters",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }
    defer result.Body.Close()

    // Create a new file with the same name as the file in S3
    out, err := os.Create(fileName)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to create a new file",
            StatusCode: 500,
        }, nil
    }
    defer out.Close()

    // Copy the downloaded file to the new file
    _, err = io.Copy(out, result.Body)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to copy the downloaded file to the new file",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s downloaded from S3", fileName),
        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 retrieves the file name from the request’s query parameters by calling request.QueryStringParameters[“fileName”], which returns the file name. If the file name is not provided, the function returns a Bad Request error message.

Write example code: AWS Lambda with Go upload CSV file

Here’s an example of an AWS Lambda function written in Go that can handle a CSV file upload to an S3 bucket:

package main

import (
    "context"
    "fmt"
    "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/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "mime/multipart"
    "io"
    "os"
    "strings"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file from the request body
    file, header, err := request.MultiValueHeaders["Content-File"][0], request.MultiValueHeaders["Content-Type"][0], request.MultiValueHeaders["Content-Disposition"][0]
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "File not found in request body",
            StatusCode: 400,
        }, nil
    }
    defer file.Close()

    // Get the file name from the request headers
    fileName := strings.Split(header, ";")[1]
    fileName = strings.TrimPrefix(fileName, " filename=")

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
        Body:   file,
    }

    // Upload the file to S3
    _, err = svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("File %s uploaded to S3", fileName),
        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 retrieves the file from the request’s body by calling request.MultiValueHeaders[“Content-File”][0] which returns the file. If the file is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to the specified S3 bucket. The function also extracts the file name from the request headers, and the bucket name is hardcoded in the code.

Write example code: AWS Lambda with Go download CSV file

Here’s an example of an AWS Lambda function written in Go that can handle a CSV file download from an S3 bucket:

package main

import (
    "context"
    "fmt"
    "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/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the request query parameters
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query parameters",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }

    // Set the response headers
    headers := make(map[string]string)
    headers["Content-Type"] = "text/csv"
    headers["Content-Disposition"] = "attachment; filename=" + fileName

    return events.APIGatewayProxyResponse{
        Body:       result.Body.(io.ReadCloser),
        StatusCode: http.StatusOK,
        Headers: headers,
    }, 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 retrieves the file name from the request’s query parameters by calling request.QueryStringParameters[“fileName”]. If the file name is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the GetObject method to download the file from the specified S3 bucket. The function also sets the response headers to indicate that the response is a csv file and it is an attachment. The bucket name is hardcoded in the code.

Example code: AWS Lambda with Go upload Excel file

Here’s an example of an AWS Lambda function written in Go that can handle an Excel file upload to an S3 bucket:

package main

import (
    "context"
    "fmt"
    "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/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
    "os"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name and file content from the request body
    fileName := request.Headers["fileName"]
    fileContent := request.Body
    if fileName == "" || fileContent == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name or content not provided in request body",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 PutObjectInput with the file details
    input := &s3.PutObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
        Body:   strings.NewReader(fileContent),
    }

    // Upload the file to S3
    _, err := svc.PutObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to upload file to S3",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       "File uploaded successfully",
        StatusCode: http.StatusOK,
    }, 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 retrieves the file name and file content from the request body by calling request.Headers[“fileName”] and request.Body respectively. If the file name or content is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the PutObject method to upload the file to the specified S3 bucket with the provided file name. The function also sets the response headers to indicate that the response is a excel file and it is an attachment. The bucket name is hardcoded in the code.

Example code: AWS Lambda with Go download Excel file

Here’s an example of an AWS Lambda function written in Go that can handle an Excel file download from an S3 bucket:

package main

import (
    "context"
    "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/s3"
    "github.com/aws/aws-lambda-go/lambda"
    "net/http"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    // Get the file name from the query string
    fileName := request.QueryStringParameters["fileName"]
    if fileName == "" {
        return events.APIGatewayProxyResponse{
            Body:       "File name not provided in query string",
            StatusCode: 400,
        }, nil
    }

    // Create an S3 session
    sess := session.Must(session.NewSession())
    svc := s3.New(sess)

    // Create an S3 GetObjectInput with the file details
    input := &s3.GetObjectInput{
        Bucket: aws.String("my-bucket"),
        Key:    aws.String(fileName),
    }

    // Download the file from S3
    result, err := svc.GetObject(input)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to download file from S3",
            StatusCode: 500,
        }, nil
    }

    // Get the file content
    fileContent, err := ioutil.ReadAll(result.Body)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to read file content",
            StatusCode: 500,
        }, nil
    }

    // Set the response headers to indicate that the response is a excel file and it is an attachment
    headers := make(map[string]string)
    headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    headers["Content-Disposition"] = "attachment; filename="+fileName

    return events.APIGatewayProxyResponse{
        Body:       string(fileContent),
        StatusCode: http.StatusOK,
        Headers: headers,
    }, 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 retrieves the file name from the query string by calling request.QueryStringParameters[“fileName”]. If the file name is not provided, the function returns a Bad Request error message.
Then it creates an S3 session using AWS SDK and calls the GetObject method to download the file from the specified S3 bucket with the provided file name. The function also sets the response headers to indicate that the response is a excel

How to build AWS Lambda with Go example code: Post/Get/Put/Delete

How to build AWS Lambda with Go example code

To build an AWS Lambda function with Go, you will need to do the following:

1. Install the AWS SDK for Go by running go get -u github.com/aws/aws-sdk-go
2. Create a new Go file for your Lambda function, and import the necessary packages from the AWS SDK.
3. Define a function that will serve as the entry point for your Lambda function, and ensure it has the correct signature.
4. Build your Go code and create a deployment package (e.g. a ZIP file).
5. Use the AWS CLI or the AWS Lambda console to create or update your Lambda function, and provide the deployment package as the function code.

Here’s an example of a simple Lambda function written in Go:

package main

import (
"context"
"github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context) (string, error) {
return "Hello, World!", nil
}

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

Note: you will also need to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Post Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a POST request:

package main

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

type Request struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    var req Request
    json.Unmarshal([]byte(request.Body), &req)
    fmt.Printf("Received request: %+v\n", req)

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s! Your age is %d", req.Name, req.Age),
        StatusCode: 200,
    }
    return response, 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 parses the incoming JSON payload in the request body and Unmarshals the json data into struct Request.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message including the Name and Age field from the request body.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Get Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a GET request:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    queryParams := request.QueryStringParameters

    name, ok := queryParams["name"]
    if !ok {
        name = "World"
    }

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s!", name),
        StatusCode: 200,
    }
    return response, 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 retrieves the value of the “name” query parameter from the request object and if it’s not present, it defaults to “World”. It then creates a response in the form of events.APIGatewayProxyResponse which contains a message using the name parameter.

You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Build Aws Lambda with Put Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a PUT request:

package main

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

type Request struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    var req Request
    json.Unmarshal([]byte(request.Body), &req)
    fmt.Printf("Received request: %+v\n", req)

    response := events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Hello, %s! Your age is %d", req.Name, req.Age),
        StatusCode: 200,
    }
    return response, nil
}

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

This example is similar to the previous POST request example. 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 parses the incoming JSON payload in the request body and Unmarshals the json data into struct Request.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message including the Name and Age field from the request body.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.
Please note that in a PUT request, it is a common practice to update the existing data instead of creating a new one. You can use DynamoDB or other data storage service to store and update the data.

Build Aws Lambda with Delete Request using Go example code

Here’s an example of an AWS Lambda function written in Go that can handle a DELETE request:

package main

import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    pathParams := request.PathParameters

    id, ok := pathParams["id"]
    if !ok {
        return events.APIGatewayProxyResponse{
            Body:       "Missing id in path",
            StatusCode: 400,
        }, nil
    }

    // Delete the item with the given id from your data store
    err := deleteItem(id)
    if err != nil {
        return events.APIGatewayProxyResponse{
            Body:       "Failed to delete item",
            StatusCode: 500,
        }, nil
    }

    return events.APIGatewayProxyResponse{
        Body:       fmt.Sprintf("Item with id %s deleted", id),
        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 retrieves the value of the “id” path parameter from the request object and if it’s not present, returns a Bad Request error message . It then calls deleteItem function which deletes the item with the given id from your data store.
In the deleteItem function you can use DynamoDB or other data storage service to delete the data.
It then creates a response in the form of events.APIGatewayProxyResponse which contains a message about the deleted item.
You can build this code and create a deployment package using the command GOOS=linux go build -o main and then create a zip file.
You can then use the AWS CLI or the AWS Lambda console to create or update your Lambda function and provide the deployment package as the function code.
Please also remember to create a IAM role for your Lambda function giving it the necessary permissions to access other AWS services, if any.

Lambda AWS SageMaker example code: python, nodejs, Java

What is AWS SageMaker?

Amazon SageMaker is a fully managed machine learning service provided by Amazon Web Services (AWS) that enables developers and data scientists to quickly and easily build, train, and deploy machine learning models.

SageMaker provides a variety of features and capabilities, including:

– Easy model creation: SageMaker provides pre-built algorithms and frameworks that can be used to quickly train and deploy machine learning models. It also supports custom algorithms and frameworks, such as TensorFlow, PyTorch, and MXNet.
– Scalable infrastructure: SageMaker automatically provisions and manages the infrastructure required to train and deploy models, including compute resources and storage.
– Model deployment: SageMaker makes it easy to deploy trained models to a variety of environments, including the SageMaker hosting environment, AWS Lambda, and EC2.
– Monitoring and management: SageMaker provides tools for monitoring and managing machine learning workflows, including tracking metrics, debugging, and troubleshooting.
– Collaboration and sharing: SageMaker provides features for collaboration and sharing, such as sharing notebooks and models with other users.
– SageMaker also provides the capability to use pre-trained models, such as ChatGPT, which can be fine-tuned to specific use cases. This allows developers and data scientists to quickly build and deploy models without having to start from scratch.

In summary, SageMaker is a comprehensive machine learning platform that provides an easy way to build, train, and deploy machine learning models with the scalability and security of the AWS infrastructure.

Python Lambda AWS SageMaker example code

Sure, here is an example of an AWS Lambda function that uses Amazon SageMaker to invoke a pre-trained model and return the result:

import json
import boto3

def lambda_handler(event, context):
    # Connect to SageMaker runtime
    sagemaker_runtime = boto3.client('runtime.sagemaker')

    # Get the input text from the event
    input_text = event['input_text']

    # Invoke the pre-trained model
    response = sagemaker_runtime.invoke_endpoint(
        EndpointName='chatgpt-endpoint',
        Body=input_text.encode('utf-8'),
        ContentType='application/json'
    )

    # Get the response from the model
    result = json.loads(response['Body'].read().decode('utf-8'))
    return result

This example assumes that you have already set up an endpoint for your pre-trained model in Amazon SageMaker and the endpoint name is ‘chatgpt-endpoint’.

In this example, the function takes an event and a context as input, the input text is extracted from the event using the key ‘input_text’ and passed as input to the sagemaker_runtime.invoke_endpoint method. The result of the model is returned by the function in form of a json object.

Please note that this is just an example and it may not work as is, it would require additional code and setup to make it work in your environment. Additionally, you may need to consider other factors, such as error handling, security and performance, depending on your specific use case.

Also, make sure that the IAM role associated with the lambda has the permission to access SageMaker and Lambda.

Java Lambda AWS SageMaker example code

Sure, here is an example of an AWS Lambda function written in Java that uses Amazon SageMaker to invoke a pre-trained model and return the result:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.sagemakerruntime.AmazonSageMakerRuntime;
import com.amazonaws.services.sagemakerruntime.AmazonSageMakerRuntimeClientBuilder;
import com.amazonaws.services.sagemakerruntime.model.InvokeEndpointRequest;
import com.amazonaws.services.sagemakerruntime.model.InvokeEndpointResult;
import java.nio.charset.StandardCharsets;

public class LambdaFunctionHandler implements RequestHandler {

    @Override
    public String handleRequest(Object input, Context context) {
        // Connect to SageMaker runtime
        AmazonSageMakerRuntime sagemakerRuntime = AmazonSageMakerRuntimeClientBuilder.defaultClient();

        // Get the input text from the input object
        String inputText = (String) input;

        // Invoke the pre-trained model
        InvokeEndpointRequest request = new InvokeEndpointRequest()
            .withEndpointName("chatgpt-endpoint")
            .withContentType("application/json")
            .withAccept("application/json")
            .withBody(inputText);
        InvokeEndpointResult response = sagemakerRuntime.invokeEndpoint(request);

        // Get the response from the model
        return new String(response.getBody().array(), StandardCharsets.UTF_8);
    }
}

This example assumes that you have already set up an endpoint for your pre-trained model in Amazon SageMaker and the endpoint name is ‘chatgpt-endpoint’. In this example, the function takes an object as input, the input text is extracted from the object, and passed as input to the sagemakerRuntime.invokeEndpoint method. The result of the model is returned by the function in form of a string.

Please note that this is just an example and it may not work as is, it would require additional code and setup to make it work in your environment. Additionally, you may need to consider other factors, such as error handling, security and performance, depending on your specific use case.

Also, make sure that the IAM role associated with the lambda has the permission to access SageMaker and Lambda.

Nodejs Lambda AWS SageMaker example code

Sure, here is an example of an AWS Lambda function written in Node.js that uses Amazon SageMaker to invoke a pre-trained model and return the result:

const AWS = require('aws-sdk');
const sagemakerRuntime = new AWS.SageMakerRuntime({apiVersion: '2017-05-13'});

exports.handler = async (event) => {
    // Get the input text from the event
    const inputText = event.input_text;

    // Invoke the pre-trained model
    const params = {
        EndpointName: "chatgpt-endpoint",
        Body: inputText,
        ContentType: "application/json",
        Accept: "application/json"
    };
    const response = await sagemakerRuntime.invokeEndpoint(params).promise();

    // Get the response from the model
    const result = response.Body.toString('utf-8');

    return result;
};

This example assumes that you have already set up an endpoint for your pre-trained model in Amazon SageMaker and the endpoint name is ‘chatgpt-endpoint’. In this example, the function takes an event as input, the input text is extracted from the event using the key ‘input_text’ and passed as input to the sagemakerRuntime.invokeEndpoint method. The result of the model is returned by the function in form of a string.

Please note that this is just an example and it may not work as is, it would require additional code and setup to make it work in your environment. Additionally, you may need to consider other factors, such as error handling, security and performance, depending on your specific use case.

Also, make sure that the IAM role associated with the lambda has the permission to access SageMaker and Lambda.

AWS SageMaker cost

The cost of using Amazon SageMaker depends on several factors, including the type and number of instances used for training and inference, the amount of data stored, and the usage of additional services.

There are three main components that make up the cost of using SageMaker:

Compute: This includes the cost of running instances for training and inference, as well as the cost of using SageMaker’s built-in algorithms and frameworks.

Storage: This includes the cost of storing data in Amazon S3, as well as the cost of using SageMaker’s data management features.

Other Services: This includes the cost of using additional services such as data preparation, data labeling, and data management.

Additionally, you’ll be charged for data transfer out of the region, as well as for data stored by SageMaker.

You can use the AWS pricing calculator to estimate the cost of using SageMaker for your specific use case. The pricing calculator allows you to select different instance types, configure storage and data transfer options, and estimate the cost of using additional services.

It’s also important to note that if you choose to use a pre-trained model such as ChatGPT, you’ll be charged for the usage of the model, and if you fine-tune it, the cost of the instances used for fine-tuning.

In general, the cost of using SageMaker can vary greatly depending on the specific use case, so it’s important to monitor usage and adjust instances and other resources as needed to keep costs under control.

SageMaker with ChatGPT example code

Here is an example of using Amazon SageMaker to fine-tune a pre-trained ChatGPT model and deploy it as an endpoint:

import boto3

# Connect to SageMaker
sagemaker = boto3.client('sagemaker')

# Specify the S3 location of the pre-trained model and the location to save the fine-tuned model
model_data = 's3://path/to/pre-trained/model'
output_path = 's3://path/to/save/fine-tuned/model'

# Specify the training job name and the location of the training data
job_name = 'chatgpt-fine-tuning-job'
training_data = 's3://path/to/training/data'

# Create the training job
response = sagemaker.create_training_job(
    TrainingJobName=job_name,
    AlgorithmSpecification={
        'TrainingImage': 'openai/gpt-2:latest',
        'TrainingInputMode': 'File'
    },
    RoleArn='arn:aws:iam::ACCOUNT_ID:role/service-role/AmazonSageMaker-ExecutionRole-20210101T000000',
    InputDataConfig=[
        {
            'ChannelName': 'train',
            'DataSource': {
                'S3DataSource': {
                    'S3DataType': 'S3Prefix',
                    'S3Uri': training_data,
                    'S3DataDistributionType': 'FullyReplicated'
                }
            },
            'ContentType': 'text/plain',
            'CompressionType': 'None'
        }
    ],
    OutputDataConfig={
        'S3OutputPath': output_path
    },
    ResourceConfig={
        'InstanceType': 'ml.p3.2xlarge',
        'InstanceCount': 1,
        'VolumeSizeInGB': 50
    },
    StoppingCondition={
        'MaxRuntimeInSeconds': 86400
    },
    HyperParameters={
        'model_name': 'text-davinci-002',
        'overwrite_output_dir': 'True'
    }
)

# Wait for the training job to complete
sagemaker.get_waiter('training_job_completed_or_stopped').wait(TrainingJobName=job_name)

# Create an endpoint configuration
response = sagemaker.create_endpoint_config(
    EndpointConfigName='chatgpt-endpoint-config',
    ProductionVariants=[
        {
            'VariantName': 'chatgpt-variant',
            'ModelName': job_name,
            'InitialInstanceCount': 1,
            'InstanceType': 'ml.t2.medium'
        }
    ]
)

# Create the endpoint
response = sagemaker.create_endpoint(
    EndpointName='chatgpt-endpoint',
    EndpointConfigName='chatgpt-endpoint-config'
)

Aws Lambda Java Example Code: Post, Get, Put, Delete

Aws Lambda Java Post example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP POST request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();
        try {
            // parse the post data
            JsonNode postData = objectMapper.readTree((String) input.get("body"));

            // do something with the data
            String name = postData.get("name").asText();
            Response responseBody = new Response("Hello, " + name);

            return ApiGatewayResponse.builder()
                    .setStatusCode(200)
                    .setObjectBody(responseBody)
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        } catch (IOException e) {
            logger.log(e.getMessage());
            return ApiGatewayResponse.builder()
                    .setStatusCode(500)
                    .setObjectBody("Error while parsing input: " + e.getMessage())
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        }
    }
}

In this example, the class MyLambdaFunction implements the RequestHandler interface, which is provided by the AWS Lambda Java SDK. The class takes in two parameters: Map and Context, which represent the input to the function and the runtime context of the function, respectively.

The function uses the ObjectMapper class to parse the request body as a JSON object and extract the name property. It then creates an instance of the Response class with the message “Hello, ” + name and returns it as the response to the request.

You would need to create a new Lambda function in the AWS Lambda console and then upload the JAR file containing this code. After that, you would need to configure an API Gateway trigger to handle the incoming POST request and route it to your Lambda function.

It’s important to note that this is just a basic example and depending on your use case you might need to handle authentication, validation, error handling and other requirements.
You might also need to import the classes used on this example like com.amazonaws.services.lambda.runtime.Context, com.amazonaws.services.lambda.runtime.LambdaLogger, com.amazonaws.services.lambda.runtime.RequestHandler and other.

Aws Lambda Java Get Header example code

Here is an example of an AWS Lambda function written in Java that retrieves and parses headers from an HTTP request:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();

        // Retrieve headers from input
        Map headers = (Map)input.get("headers");

        // Parse specific header
        String myHeader = headers.get("my-header");

        // Do something with the header value
        Response responseBody = new Response("Hello, " + myHeader);

        return ApiGatewayResponse.builder()
                .setStatusCode(200)
                .setObjectBody(responseBody)
                .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                .build();
    }
}

This example retrieves the headers from the input object, which is passed as the first argument to the Lambda function. It then uses the get() method to retrieve the value of a specific header, in this case “my-header”, and save it to a variable. Then the function creates an instance of the Response class with the message “Hello, ” + myHeader and returns it as the response to the request.

You would need to create a new Lambda function in the AWS Lambda console and then upload the JAR file containing this code. After that, you would need to configure an API Gateway trigger to handle the incoming GET request and route it to your Lambda function.

It’s important to note that this is just a basic example and depending on your use case you might need to handle authentication, validation, error handling and other requirements.
You might also need to import the classes used on this example like com.amazonaws.services.lambda.runtime.Context, com.amazonaws.services.lambda.runtime.LambdaLogger, com.amazonaws.services.lambda.runtime.RequestHandler and other.

Aws Lambda Java get Example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP GET request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();

        // Retrieve query string parameters
        Map queryParams = (Map)input.get("queryStringParameters");

        // Retrieve name
        String name = queryParams.get("name");

        // Do something with the query string parameters
        Response responseBody = new Response("Hello, " + name);

        return ApiGatewayResponse.builder()
                .setStatusCode(200)
                .setObjectBody(responseBody)
                .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                .build();
    }
}

This example retrieves the query string parameters from the input object, which is passed as the first argument to the Lambda function. It then uses the get() method to retrieve the value of the name parameter and saves it to a variable. Then the function creates an instance of the Response class with the message “Hello, ” + name and returns it as the response to the request.

Aws Lambda Java Put Example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP PUT request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();
        try {
            // parse the put data
            JsonNode putData = objectMapper.readTree((String) input.get("body"));

            // do something with the data
            String name = putData.get("name").asText();
            Response responseBody = new Response("Hello, " + name);

            return ApiGatewayResponse.builder()
                    .setStatusCode(200)
                    .setObjectBody(responseBody)
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        } catch (IOException e) {
            logger.log(e.getMessage());
            return ApiGatewayResponse.builder()
                    .setStatusCode(500)
                    .setObjectBody("Error while parsing input: " + e.getMessage())
                    .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                    .build();
        }
    }
}

In this example, the class MyLambdaFunction implements the RequestHandler interface, which is provided by the AWS Lambda

Aws Lambda Java Delete Example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP DELETE request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();

        // Retrieve query string parameters
        Map queryParams = (Map)input.get("queryStringParameters");

        // Retrieve id
        String id = queryParams.get("id");

        // Delete the item
        deleteItem(id);

        // Create a response
        Response responseBody = new Response("Successfully deleted item with id: " + id);

        return ApiGatewayResponse.builder()
                .setStatusCode(200)
                .setObjectBody(responseBody)
                .setHeaders(Collections.singletonMap("X-Powered-By", "AWS Lambda & serverless"))
                .build();
    }
}

This example retrieves the query string parameters from the input object, which is passed as the first argument to the Lambda function. It then uses the get() method to retrieve the value of the id parameter and saves it to a variable. It then calls the deleteItem(id) function to delete the item from the database. Finally, it creates an instance of the Response class with the message “Successfully deleted item with id: ” + id and returns it as the response to the request.

You would need to create a new Lambda function in the AWS Lambda console and then upload the JAR file containing this code. After that, you would need to configure an API Gateway trigger to handle the incoming DELETE request and route it to your Lambda function.

Aws Lambda Java Patch example code

Here is an example of an AWS Lambda function written in Java that handles an HTTP PATCH request and returns a JSON response:

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

public class MyLambdaFunction implements RequestHandler, ApiGatewayResponse> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ApiGatewayResponse handleRequest(Map input, Context context) {
        LambdaLogger logger = context.getLogger();
        try {
            // parse the patch data
            JsonNode patchData = objectMapper.readTree((String) input.get("body"));

            // do something with the data
            String id = patchData.get("id").asText();
            String newValue = patchData.get("new_value").asText();
            updateItem(id, newValue);

            Response responseBody = new Response("Successfully updated