こんにちは、エンジニアの久保です。
弊社では2022/4 にリリースされた AWS Lambda の関数 URL(AWS Lambda FunctionURLs)を使って Lambda の開発を進めています。前回の記事では、AWS SAM で関数 URL を有効にする方法を紹介しました。
現在、社内で運用中の AWS Lambda + Amazon API Gateway で構成される WebAPI についても関数 URL を使った構成へ変更を進めています。
今回は、API Gateway と 関数 URL(FunctionURLs)を併用する場合の SAM テンプレートを作成しましたのでご紹介します。
関数 URL を利用した場合、ペイロード形式は API Gateway Version 2 となるため構成によっては注意が必要です。
クライアントが関数の URL を呼び出すと、Lambda は、まずこのリクエストをイベントオブジェクトにマップしてから、関数に受け渡します その関数の応答は、Lambda が関数 URL を介してクライアントに返信する HTTP レスポンスにマッピングされます。
このリクエストとレスポンスのイベント形式は、Amazon API Gateway ペイロード形式バージョン 2.0 と同じスキーマに従います。
なお、前回利用した SAM の hello-world テンプレートの場合、API Gateway Version 1 の形式になっています。
もしも API Gateway と関数URLのどちらも利用したい場合は、API Gateway を HTTP API に設定するとよいでしょう。以下にテンプレートの例を示します。
利用ケースとしては、「開発の際にローカル環境では sam local start-api を使って動作確認したい」などが考えられます。
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Tracing: Active
Api:
TracingEnabled: True
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs16.x
Architectures:
- x86_64
Events:
HelloWorld:
Type: HttpApi # More info about API Event Source: https://github.com/aws/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlesshttpapi
Properties:
Path: /hello
Method: GET
FunctionUrlConfig:
AuthType: NONE
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
HelloWorldFunctionUrl:
Description: "Function URLs endpoint"
Value: !GetAtt HelloWorldFunctionUrl.FunctionUrl
まとめ
今回は、Lambda で API Gateway と 関数 URL(FunctionURLs)を併用するケースの SAM テンプレートをご紹介しました。ぜひご活用いただければと思います。