如何为CDK栈中导入的现有API Gateway添加二进制媒体类型?
解决AWS CDK引用现有API Gateway后配置二进制媒体类型的问题
当通过RestApi.from_rest_api_attributes引用已创建的API Gateway时,直接修改L2类的binary_media_types属性无效——因为该方法创建的是只读引用,无法通过L2 API直接修改配置。此时需要操作底层的CloudFormation L1资源(CfnRestApi)来实现需求:
具体实现步骤
- 从引用的
RestApi实例中获取对应的底层CfnRestApi资源 - 修改
CfnRestApi的binary_media_types属性
代码示例
from aws_cdk import aws_apigateway as apigateway # 引用现有API Gateway api = apigateway.RestApi.from_rest_api_attributes(self, "API", rest_api_id="api-id", root_resource_id="root-resource-id") # 获取底层CloudFormation资源 cfn_api = api.cfn_resource # 设置允许的二进制媒体类型 cfn_api.binary_media_types = ["application/pdf", "image/*"]
补充说明
api.cfn_resource是CDK L2类提供的直接访问底层L1资源的属性(适配多数AWS CDK版本),若你的版本中无此属性,也可通过api.node.default_child获取(需显式转换为apigateway.CfnRestApi类型)。- 该操作会在部署CDK栈时,通过CloudFormation更新现有API Gateway的二进制媒体类型配置。
内容的提问来源于stack exchange,提问作者Nick A. Watts
相关产品推荐
相关产品推荐

