AWS CDK允许我们使用嵌套堆叠API网关。当需要在API网关层中添加模型验证时,需要在CDK中使用“aws-apigateway.Model”类。为了在非常规的情况下添加模型验证(例如在嵌套API网关中),我们需要使用AWS官方文档建议的“aws-apigateway.CfnModel”类。以下是一个简单的示例,演示如何使用CDK配置嵌套API网关模型验证。
from aws_cdk import (
aws_apigateway as apigateway,
aws_iam as iam,
core
)
class NestedApiGatewayStack(core.Stack):
def __init__(self, app: core.App, id: str, **kwargs):
super().__init__(app, id, **kwargs)
# 创建新的嵌套API网关
child_api_gateway = apigateway.RestApi(
self,
"ChildApiGateway",
rest_api_name="ChildApiGateway",
deploy_options={
"stage_name": "test"
}
)
# 在根API网关中添加子网关集成
# 注意:这里我们使用了CfnModel而不是原生Model类
# 这是因为原生的Model类不能在嵌套API网关中使用。
child_model = apigateway.CfnModel(
self,
"ChildModel",
rest_api_id=self.rest_api.rest_api_id,
content_type="application/json",
schema={
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"}
},
"required": ["name"]
}
)
# 在根API网关中创建子资源
child_resource = self.rest_api.root.add_resource("child")
# 在子资源上添加方法,并使用集成访问子网关
child_resource.add_method(
"GET",
apigateway.Integration(
type=apig