Create checkout_order Lambda function

In this step, we will create a new checkout_order Lambda function using a SAM template.

Preparation

  1. Open template.yaml in the source code you downloaded before.

    • Comment this code block.

      # BookApiDeployment:
      #   Type: AWS::ApiGateway::Deployment
      #   Properties:
      #     RestApiId: !Ref BookApi
      #   DependsOn:
      #     - BookApiGet
      #     - BookApiCreate
      #     - BookApiDelete
      #     - LoginApi
      #     - RegisterApi
      #     - ConfirmApi
      
      BookApiStage:
        Type: AWS::ApiGateway::Stage
        Properties:
          RestApiId: !Ref BookApi
          StageName: !Ref stage
      #     DeploymentId: !Ref BookApiDeployment
      

      Comment BookApiDeployment

  2. Run the below commands.

    sam validate
    sam build
    

    SAM validate and build

  3. Deploy the updated stack.

    sam deploy
    

    SAM deploy

  4. Wait for the deployment to complete.

    Deploy complete

Create FCAJCheckOutOrder function

Before adding the parameters, you need to get the SQS Queue URL and SNS Topic ARN from the AWS Console.
Open the SQS console and copy the URL of the checkout-queue.
Open the SNS console and copy the ARN of the order-notice topic.

SQS checkout-queue URL SNS order-notice ARN

  1. Open template.yaml in the source code you downloaded before.

    • Add the following scripts below to create FCAJCheckOutOrder function.
      • Change checkoutQueueUrl and orderTopicArn value to your value.

        checkoutQueueName:
          Type: String
          Default: checkout-queue
        
        checkoutQueueUrl:
          Type: String
          Default: https://sqs.us-east-1.amazonaws.com/017820706022/checkout-queue
        
        orderTopicName:
          Type: String
          Default: order-notice
        
        orderTopicArn:
          Type: String
          Default: arn:aws:sns:us-east-1:017820706022:order-notice
        
        checkoutPathPart:
          Type: String
          Default: order
        

        Add parameters

        FCAJCheckOutOrderFunction:
          Type: AWS::Serverless::Function
          Properties:
            CodeUri: fcaj-book-shop/checkout_order
            Handler: checkout_order.lambda_handler
            Runtime: python3.13
            FunctionName: checkout_order
            Environment:
              Variables:
                SQS_QUEUE_URL: !Ref checkoutQueueUrl
                SNS_TOPIC_ARN: !Ref orderTopicArn
            Architectures:
              - x86_64
            Policies:
              - Statement:
                  - Sid: VisualEditor0
                    Effect: Allow
                    Action:
                      - sqs:*
                    Resource:
                      - !Sub "arn:aws:sqs:${AWS::Region}:${AWS::AccountId}:${checkoutQueueName}"
                  - Sid: VisualEditor1
                    Effect: Allow
                    Action:
                      - sns:Publish
                    Resource:
                      - !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${orderTopicName}"
        

        Add FCAJCheckOutOrderFunction

        FCAJCheckoutOrderResource:
          Type: AWS::ApiGateway::Resource
          Properties:
            RestApiId: !Ref BookApi
            ParentId: !Ref BookApiResource
            PathPart: !Ref checkoutPathPart
        
        FCAJCheckoutOrderApiOptions:
          Type: AWS::ApiGateway::Method
          Properties:
            HttpMethod: OPTIONS
            RestApiId: !Ref BookApi
            ResourceId: !Ref FCAJCheckoutOrderResource
            AuthorizationType: NONE
            Integration:
              Type: MOCK
              RequestTemplates:
                application/json: '{"statusCode": 200}'
              IntegrationResponses:
                - StatusCode: "200"
                  ResponseParameters:
                    method.response.header.Access-Control-Allow-Origin: "'*'"
                    method.response.header.Access-Control-Allow-Methods: "'OPTIONS,POST,GET,DELETE'"
                    method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
            MethodResponses:
              - StatusCode: "200"
                ResponseParameters:
                  method.response.header.Access-Control-Allow-Origin: true
                  method.response.header.Access-Control-Allow-Methods: true
                  method.response.header.Access-Control-Allow-Headers: true
        

        Add FCAJCheckoutOrderResource and ApiOptions

        FCAJCheckoutOrderApi:
          Type: AWS::ApiGateway::Method
          Properties:
            HttpMethod: POST
            RestApiId: !Ref BookApi
            ResourceId: !Ref FCAJCheckoutOrderResource
            AuthorizationType: NONE
            Integration:
              Type: AWS_PROXY
              IntegrationHttpMethod: POST # For Lambda integrations, you must set the integration method to POST
              Uri: !Sub >-
                arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${FCAJCheckOutOrderFunction.Arn}/invocations
            MethodResponses:
              - StatusCode: "200"
                ResponseParameters:
                  method.response.header.Access-Control-Allow-Origin: true
                  method.response.header.Access-Control-Allow-Methods: true
                  method.response.header.Access-Control-Allow-Headers: true
        

        Add FCAJCheckoutOrderApi

        FCAJCheckoutOrderApiInvokePermission:
          Type: AWS::Lambda::Permission
          Properties:
            FunctionName: !Ref FCAJCheckOutOrderFunction
            Action: lambda:InvokeFunction
            Principal: apigateway.amazonaws.com
            SourceAccount: !Ref "AWS::AccountId"
        

        Add FCAJCheckoutOrderApiInvokePermission

  2. The directory structure is as follows.

    fcaj-book-shop
    ├── fcaj-book-shop
    │   ├── checkout_order
    │   │   └── checkout_order.py
    │   ├── ...
    └── template.yaml
    
    • Create checkout_order folder in fcaj-book-shop/fcaj-book-shop/ folder.

    • Create checkout_order.py file and copy the following code to it.

      import json
      import boto3
      import os
      
      headers = {
          "Content-Type": "application/json",
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE",
          "Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"
      }
      
      
      def lambda_handler(event, context):
          sqs = boto3.client('sqs')
          sns = boto3.client('sns')
      
          sqs_queue_url = os.environ['SQS_QUEUE_URL']
          sns_topic_arn = os.environ['SNS_TOPIC_ARN']
          sns_topic_subject = "New order received. Please process."
      
          try:
              body = json.loads(event['body'])
      
              print(f"body: {body}")
      
              # Send to SQS
              sqs_response = sqs.send_message(
                  QueueUrl=sqs_queue_url,
                  MessageBody=json.dumps(body)
              )
      
              # Send to SNS
              sns_response = sns.publish(
                  TopicArn=sns_topic_arn,
                  Message=f"New order received: {json.dumps(body)}",
                  Subject=sns_topic_subject
              )
      
              return {
                  'statusCode': 200,
                  'headers': headers,
                  'body': json.dumps({
                      'message': 'Order processed successfully',
                      'sqs_message_id': sqs_response['MessageId'],
                      'sns_message_id': sns_response['MessageId']
                  })
              }
      
          except Exception as e:
              print(f"Error processing order: {e}")
              raise Exception(f"Error processing order: {e}")
      

      checkout_order.py

  3. Uncomment this code block.

    BookApiDeployment:
      Type: AWS::ApiGateway::Deployment
      Properties:
        RestApiId: !Ref BookApi
      DependsOn:
        - BookApiGet
        - BookApiCreate
        - BookApiDelete
        - LoginApi
        - RegisterApi
        - ConfirmApi
        - FCAJCheckoutOrderApi
    
    BookApiStage:
      Type: AWS::ApiGateway::Stage
      Properties:
        RestApiId: !Ref BookApi
        StageName: !Ref stage
        DeploymentId: !Ref BookApiDeployment
    

    Uncomment BookApiDeployment

  4. Run the below commands.

    sam validate
    sam build
    

    SAM validate and build

  5. Deploy the updated stack.

    sam deploy
    

    SAM deploy with FCAJCheckoutOrder

  6. Wait for the deployment to complete.

    Deploy complete

Check the creation

  1. Open Amazon API Gateway console.

    • Click fcaj-serverless-api. API Gateway list
    • Click Resources on the left menu.
    • Check /order just created. API Gateway Resources
  2. Open Amazon Lambda console.

    • Click Functions on the left menu.
    • Choose checkout_order function. Lambda Functions list
    • At checkout_order page, check the function that just created. checkout_order function detail