Search code examples
amazon-web-servicesaws-api-gatewayamazon-cognitocustom-headerschalice

Adding Headers to AWS API Gateway Response using Chalice


My use-case requires my app to return CORS headers when error response is 401.

This functionality was added by AWS last year (See this). It can be done using Cloudformation and Swagger template but I'm not sure if it's yet possible with Chalice.


Solution

  • I solved my problem by using a python script that adds the CORS headers for 401 response and redeploys the API. This redeploying of API takes a second or two since it doesn't have to deploy all Lambdas like Chalice.

    deploy.sh

    #!/usr/bin/env bash
    
    cd services
    A="$(chalice deploy --stage $1)"
    cd ..
    python update_api_response_headers.py "$A" "$1"
    

    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 folder contains my chalice app. deploy.sh and update_api_response_headers.py are placed one level above the chalice app. To deploy the app I simply have to use:

    ./deploy.sh stage_name