import boto3
def add_cors_headers_to_gateway_responses(api_id, region):
client = boto3.client('apigateway', region_name=region)
# Define the CORS headers
cors_headers = {
'Access-Control-Allow-Origin': "'*'",
'Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'",
'Access-Control-Allow-Methods': "'GET,OPTIONS,POST,PUT'"
}
# Update default 4xx response
client.update_gateway_response(
restApiId=api_id,
responseType='DEFAULT_4XX',
patchOperations=[
{
'op': 'add',
'path': '/responseParameters/gatewayresponse.header.Access-Control-Allow-Origin',
'value': "'*'"
},
{
'op': 'add',
'path': '/responseParameters/gatewayresponse.header.Access-Control-Allow-Headers',
'value': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
},
{
'op': 'add',
'path': '/responseParameters/gatewayresponse.header.Access-Control-Allow-Methods',
'value': "'GET,OPTIONS,POST,PUT'"
}
]
)
# Update default 5xx response
client.update_gateway_response(
restApiId=api_id,
responseType='DEFAULT_5XX',
patchOperations=[
{
'op': 'add',
'path': '/responseParameters/gatewayresponse.header.Access-Control-Allow-Origin',
'value': "'*'"
},
{
'op': 'add',
'path': '/responseParameters/gatewayresponse.header.Access-Control-Allow-Headers',
'value': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
},
{
'op': 'add',
'path': '/responseParameters/gatewayresponse.header.Access-Control-Allow-Methods',
'value': "'GET,OPTIONS,POST,PUT'"
}
]
)
print("CORS headers added to DEFAULT_4XX and DEFAULT_5XX gateway responses.")
# Usage
api_id = 'your-api-id'
region = 'your-region'
add_cors_headers_to_gateway_responses(api_id, region)
Created
January 28, 2025 17:17
-
-
Save edwardoboh/06684ff8d78402e9edb999e39c5425db to your computer and use it in GitHub Desktop.
This code snippet shows how to configure cors headers on default 4XX and 5XX gateway response. This adding is neccessary for configuring CORS via the boto3 SDK
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment