Last active
September 2, 2023 07:18
-
-
Save ankur0101/07b6bf34a8b78d41551d61e3a12085d1 to your computer and use it in GitHub Desktop.
AWS API Gateway resource CORS configuration updater
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
# Initialize the Boto3 client for API Gateway | |
client = boto3.client('apigateway') | |
# Define the API Gateway resource ID and the new CORS settings | |
resource_id = 'your-resource-id' | |
new_cors_settings = { | |
"allowOrigins": ['https://example.com'], | |
"allowHeaders": ['Authorization', 'Content-Type'], | |
"exposeHeaders": ['ETag'], | |
"maxAge": 3600, | |
"allowCredentials": True, | |
"allowMethods": ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] | |
} | |
# Update the CORS configuration for the resource | |
response = client.update_method_settings( | |
restApiId='your-rest-api-id', | |
resourceId=resource_id, | |
httpMethod='OPTIONS', | |
patchOperations=[ | |
{ | |
'op': 'replace', | |
'path': '/responseParameters/method.response.header.Access-Control-Allow-Origin', | |
'value': f"'{','.join(new_cors_settings['allowOrigins'])}'" | |
}, | |
{ | |
'op': 'replace', | |
'path': '/responseParameters/method.response.header.Access-Control-Expose-Headers', | |
'value': f"'{','.join(new_cors_settings['exposeHeaders'])}'" | |
}, | |
{ | |
'op': 'replace', | |
'path': '/responseParameters/method.response.header.Access-Control-Max-Age', | |
'value': str(new_cors_settings['maxAge']) | |
}, | |
{ | |
'op': 'replace', | |
'path': '/responseParameters/method.response.header.Access-Control-Allow-Credentials', | |
'value': str(new_cors_settings['allowCredentials']).lower() | |
} | |
] | |
) | |
print("CORS settings updated successfully:", response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment