Trong bước này, chúng ta sẽ thêm phương thức GET vào REST API để frontend có thể lấy danh sách sách từ hàm Lambda books_list. Chúng ta cũng sẽ tạo API deployment và một stage staging để endpoint có thể truy cập qua URL công khai.
Mở tệp template.yaml trong thư mục fcaj-book-shop.
Thêm tham số stage vào phần Parameters. Tham số này kiểm soát tên deployment stage được sử dụng:
stage:
Type: String
Default: staging

Thêm các tài nguyên sau vào phần Resources để tạo phương thức GET và deployment của nó:
BookApiGet:
Type: AWS::ApiGateway::Method
Properties:
HttpMethod: GET
RestApiId: !Ref BookApi
ResourceId: !Ref BookApiResource
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/${BooksList.Arn}/invocations
IntegrationResponses:
- StatusCode: "200"
ResponseParameters:
method.response.header.Access-Control-Allow-Origin: "'*'"
method.response.header.Access-Control-Allow-Methods: "'GET,POST,OPTIONS'"
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: "'*'"
method.response.header.Access-Control-Allow-Methods: "'GET,POST,OPTIONS'"
method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
BookApiDeployment:
Type: AWS::ApiGateway::Deployment
Properties:
RestApiId: !Ref BookApi
DependsOn:
- BookApiGet

Tiếp tục thêm tài nguyên stage và invoke permission ngay sau BookApiDeployment:
BookApiStage:
Type: AWS::ApiGateway::Stage
Properties:
RestApiId: !Ref BookApi
StageName: !Ref stage
DeploymentId: !Ref BookApiDeployment
BookApiGetInvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !Ref BooksList
Action: lambda:InvokeFunction
Principal: apigateway.amazonaws.com
SourceAccount: !Ref "AWS::AccountId"

Chạy các lệnh sau để validate và build SAM template:
sam validate
sam build

Triển khai stack đã cập nhật:
sam deploy
Changeset sẽ hiển thị các tài nguyên mới được thêm:
BookApiGet (AWS::ApiGateway::Method)BookApiDeployment (AWS::ApiGateway::Deployment)BookApiStage (AWS::ApiGateway::Stage)BookApiGetInvokePermission (AWS::Lambda::Permission)Nhập y để xác nhận triển khai.

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

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

Tại trang fcaj-serverless-api:
/books.
Nhấp vào Stages trong menu bên trái.
Ví dụ:
https://1bupjnr42d.execute-api.ap-southeast-1.amazonaws.com/staging/books
