使用 Chalice 添加 Headers 到 AWS API 网关响应

Adding Headers to AWS API Gateway Response using Chalice

当错误响应为 401 时,我的 use-case 要求我的应用 return CORS headers。

此功能是 AWS 去年添加的 (See this)。可以使用 Cloudformation 和 Swagger 模板来完成,但我不确定是否可以使用 Chalice。

我通过使用 python 脚本解决了我的问题,该脚本为 401 响应添加了 CORS headers 并重新部署了 API。 API 的重新部署需要一两秒钟,因为它不必像 Chalice 那样部署所有 Lambda。

deploy.sh

#!/usr/bin/env bash

cd services
A="$(chalice deploy --stage )"
cd ..
python update_api_response_headers.py "$A" ""

update_api_response_headers.py

import boto3
import sys
import re

if len(sys.argv) != 3:
    print("usage: python script.py <CHALICE_DEPLOYMENT_RESULT> <STAGE>")
    exit()

search = re.search('URL: https:\/\/([a-zA-Z0-9]+).+', sys.argv[1])
api_id = search.group(1)
print(api_id)
if not api_id:
    print(sys.argv[1])
    exit()
client = boto3.client('apigateway')

response = client.put_gateway_response(
    restApiId=api_id,
    responseType='UNAUTHORIZED',
    statusCode='401',
    responseParameters={
        "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
        "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
    }
)
response = client.create_deployment(
    restApiId=api_id,
    stageName=sys.argv[2])

print(sys.argv[1])

Services 文件夹包含我的圣杯应用程序。 deploy.shupdate_api_response_headers.py 放置在圣杯应用程序上方一层。要部署应用程序,我只需使用:

./deploy.sh stage_name