Skip to content

Instantly share code, notes, and snippets.

@ankur0101
Last active September 2, 2023 07:18
Show Gist options
  • Save ankur0101/07b6bf34a8b78d41551d61e3a12085d1 to your computer and use it in GitHub Desktop.
Save ankur0101/07b6bf34a8b78d41551d61e3a12085d1 to your computer and use it in GitHub Desktop.
AWS API Gateway resource CORS configuration updater
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