Create delete_order Lambda function

In this step, we will create a new delete_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
      #     - FCAJCheckoutOrderApi
      #     - FCAJOrderManagementApi
      #     - FCAJHandleOrderApi
      
      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 FCAJDeleteOrder function

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

    • Add the following scripts below to create FCAJDeleteOrder function.

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

      Add FCAJDeleteOrderFunction

      FCAJDeleteOrderApi:
        Type: AWS::ApiGateway::Method
        Properties:
          HttpMethod: DELETE
          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/${FCAJDeleteOrderFunction.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
      
      FCAJDeleteOrderApiInvokePermission:
        Type: AWS::Lambda::Permission
        Properties:
          FunctionName: !Ref FCAJDeleteOrderFunction
          Action: lambda:InvokeFunction
          Principal: apigateway.amazonaws.com
          SourceAccount: !Ref "AWS::AccountId"
      

      Add FCAJDeleteOrderApi and InvokePermission

  2. The directory structure is as follows.

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

    • Create delete_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"
      }
      
      sqs = boto3.client('sqs')
      
      # Get value of the environment variables
      queue_url = os.getenv('SQS_QUEUE_URL')
      
      
      def lambda_handler(event, context):
          order = json.loads(event['body'])
      
          try:
              if 'receiptHandle' in order and order['receiptHandle']:
                  sqs.delete_message(
                      QueueUrl=queue_url,
                      ReceiptHandle=order['receiptHandle']
                  )
      
              else:
                  raise Exception("No receiptHandle provided")
      
          except Exception as e:
              print(f"Error deleting order: {e}")
              raise Exception(f"Error deleting order: {e}")
      
          return {
              'statusCode': 200,
              'headers': headers,
              'body': json.dumps('Order deleted successfully')
          }
      

      delete_order.py

  3. Uncomment this code block.

    BookApiDeployment:
      Type: AWS::ApiGateway::Deployment
      Properties:
        RestApiId: !Ref BookApi
      DependsOn:
        - BookApiGet
        - BookApiCreate
        - BookApiDelete
        - LoginApi
        - RegisterApi
        - ConfirmApi
        - FCAJCheckoutOrderApi
        - FCAJOrderManagementApi
        - FCAJHandleOrderApi
        - FCAJDeleteOrderApi
    
    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 FCAJDeleteOrder

  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 resource with DELETE, GET, OPTIONS, POST methods. API Gateway Resources
  2. Open Amazon Lambda console.

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