Tạo DELETE API

Trong bước này, chúng ta sẽ thêm phương thức DELETE để cho phép frontend xóa sách theo ID thông qua hàm Lambda book_delete.

Endpoint DELETE sử dụng path parameter (/books/{id}), đã được định nghĩa bởi resource BookDeleteApiResource. Giống như bước POST trước, việc thêm method mới yêu cầu tạo lại API deployment theo hai giai đoạn.

Chúng ta cũng thêm resource BookApiDeleteOptions (MOCK integration) để hỗ trợ preflight CORS request từ trình duyệt cho endpoint này.

Giai đoạn 1 — Xóa Deployment cũ

  1. Mở tệp template.yaml trong thư mục fcaj-book-shop.

  2. Comment out khối BookApiDeployment và dòng DeploymentId trong BookApiStage:

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

    Comment BookApiDeployment

  3. Chạy các lệnh để validate, build và deploy:

    sam validate
    sam build
    

    SAM Validate & Build - Giai đoạn 1

    sam deploy
    

    Changeset hiển thị:

    • Modify BookApiStage
    • Delete BookApiDeployment

    Nhập y để xác nhận.

    SAM Deploy - Changeset Giai đoạn 1

  4. Chờ quá trình triển khai hoàn tất.

    Deploy hoàn tất - Giai đoạn 1

Giai đoạn 2 — Thêm DELETE Method và Deploy lại

  1. Thêm resource BookApiDelete. Lưu ý rằng ResourceId tham chiếu đến BookDeleteApiResource (đường dẫn /{id}), không phải BookApiResource:

    BookApiDelete:
      Type: AWS::ApiGateway::Method
      Properties:
        HttpMethod: DELETE
        RestApiId: !Ref BookApi
        ResourceId: !Ref BookDeleteApiResource
        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/${BookDelete.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
    

    BookApiDelete resource

  2. Thêm BookApiDeleteOptions (MOCK integration cho CORS preflight) và BookApiDeleteInvokePermission:

    BookApiDeleteOptions:
      Type: AWS::ApiGateway::Method
      Properties:
        HttpMethod: OPTIONS
        RestApiId: !Ref BookApi
        ResourceId: !Ref BookDeleteApiResource
        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: "'GET,POST,OPTIONS,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
    
    BookApiDeleteInvokePermission:
      Type: AWS::Lambda::Permission
      Properties:
        FunctionName: !Ref BookDelete
        Action: lambda:InvokeFunction
        Principal: apigateway.amazonaws.com
        SourceAccount: !Ref "AWS::AccountId"
    

    BookApiDeleteOptions và BookApiDeleteInvokePermission

Tại sao cần thêm method OPTIONS?: Trình duyệt gửi preflight OPTIONS request trước khi thực hiện DELETE request từ origin khác (chính sách CORS). Nếu không có MOCK integration này, trình duyệt sẽ chặn lệnh gọi DELETE ngay trước khi đến Lambda. BookApiDeleteOptions cung cấp phản hồi tĩnh cho phép trình duyệt tiếp tục.

  1. Bỏ comment khối BookApiDeploymentDeploymentId. Cập nhật DependsOn để bao gồm cả ba methodBookApiGet, BookApiCreate, và BookApiDelete:

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

    Bỏ comment BookApiDeployment với đủ ba DependsOn

  2. Chạy lại các lệnh để build và deploy:

    sam validate
    sam build
    

    SAM Validate & Build - Giai đoạn 2

    sam deploy
    

    Changeset hiển thị các tài nguyên mới:

    • Add BookApiDelete (AWS::ApiGateway::Method)
    • Add BookApiDeleteOptions (AWS::ApiGateway::Method)
    • Add BookApiDeployment (AWS::ApiGateway::Deployment)
    • Add BookApiDeleteInvokePermission (AWS::Lambda::Permission)
    • Modify BookApiStage (AWS::ApiGateway::Stage)

    Nhập y để xác nhận.

    SAM Deploy - Changeset Giai đoạn 2

  3. Chờ quá trình triển khai hoàn tất. Bạn sẽ thấy Successfully created/updated stack - fcaj-book-shop in ap-southeast-1.

    Deploy hoàn tất - Giai đoạn 2

Kiểm tra trên AWS Console

  1. Mở AWS API Gateway console. Nhấp vào fcaj-serverless-api REST API.

    API Gateway - fcaj-serverless-api

  2. Tại trang fcaj-serverless-api:

    • Nhấp vào Resources trong menu bên trái.
    • Mở rộng /books/{id} → chọn DELETE.
    • Nhấp vào tooltip Lambda integration — xác nhận hàm được tích hợp là book_delete.

    Resources - DELETE /books/{id} - Lambda integration book_delete

  3. Nhấp vào Stages trong menu bên trái.

    • Mở rộng staging/books/{id} → chọn DELETE.
    • Sao chép và lưu lại Invoke URL.

    Ví dụ: https://1bupjnr42d.execute-api.ap-southeast-1.amazonaws.com/staging/books/{id}

    Stages - staging/DELETE /books/{id} - Invoke URL