Home > Net >  Enable CORS on API Gateway with Python CDK
Enable CORS on API Gateway with Python CDK

Time:02-10

I have an API Gateway defined in the python cdk that will accept CURL Restful requests to upload / read / delete files from an S3 bucket:

api = api_gw.RestApi(self, "file-api",
                  rest_api_name="File REST Service")
        
        file = api.root.add_resource("{id}")
        
        get_files_integration = api_gw.LambdaIntegration(handler,
                request_templates={"application/json": '{ "statusCode": "200" }'})
        post_file_integration = api_gw.LambdaIntegration(handler)
        get_file_integration = api_gw.LambdaIntegration(handler)
        delete_file_integration = api_gw.LambdaIntegration(handler)
        
        api.root.add_method("GET", get_files_integration, authorization_type=api_gw.AuthorizationType.COGNITO, authorizer=auth)
        file.add_method("POST", post_file_integration);     # POST /{id}
        file.add_method("GET", get_file_integration);       # GET /{id}
        file.add_method("DELETE", delete_file_integration); # DELETE /{id}  

Is it possible to enable CORS on the API Gateway so that it will perform pre-flight checks and allow external access from a localhost on another machine?

I have attempted to use the existing add_core_preflight() method defined in the documentation I can find but believe this may no longer be valid as of CDK 2.0.

CodePudding user response:

Yes, IResource.add_cors_preflight() does exactly this.

You can also specify default CORS config with the default_cors_preflight_options attribute of RestApi.

Here are the examples from the docs. They're in Typescript, but it will work the same in Python.

The following example will enable CORS for all methods and all origins on all resources of the API:

new apigateway.RestApi(this, 'api', {
  defaultCorsPreflightOptions: {
    allowOrigins: apigateway.Cors.ALL_ORIGINS,
    allowMethods: apigateway.Cors.ALL_METHODS // this is also the default
  }
})

The following example will add an OPTIONS method to the myResource API resource, which only allows GET and PUT HTTP requests from the origin https://amazon.com.

declare const myResource: apigateway.Resource;

myResource.addCorsPreflight({
  allowOrigins: [ 'https://amazon.com' ],
  allowMethods: [ 'GET', 'PUT' ]
});
  • Related