目次 †
概要 †API Gateway & Lambda でバイナリレスポンスを返却する場合の覚え書き。 ポイントは以下の3点
注意) フォルダ/ファイル構成 †/work Lambda †./src/index.py import base64 def handler(event, context): with open("sample1.png", "rb") as f: bytes_image = f.read() encoded_image = base64.b64encode(bytes_image).decode("utf-8") return { "statusCode": 200, "headers": {"Content-Type": "image/png"}, "isBase64Encoded": True, "body": encoded_image } CloudFormationテンプレート †[参考] ./template.yml AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Description: "バイナリデータを返却する API Gateway & Lambda" Resources: ImageResponseApi: Type: AWS::Serverless::Api Properties: Name: ImageResponseApi StageName: Prod BinaryMediaTypes: - "image/*" ImageResponseFunction: Type: AWS::Serverless::Function Properties: FunctionName: ImageResponseFunction CodeUri: ./src Handler: index.handler Runtime: python3.6 Events: GetRoot: Type: Api Properties: RestApiId: !Ref ImageResponseApi Path: / Method: get Outputs: ImageResponseApiUrl: Value: !Sub "https://${ImageResponseApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/" Export: Name: ImageResponseApiUrl デプロイ †確認 †ブラウザからURLを直接叩いても、Acceptヘッダは付かないので注意が必要。 curl から Acceptヘッダ付きのリクエストを発行して確認。(レスポンスはバイナリなのでファイルに出力) curl -H "Accept: image/png" --output test.png 対象のAPIのURL もしくは、以下の様な簡単なHTMLで確認しても良い。 <!doctype html> <html> <img src="対象のAPIのURL"> </html> |