如何通过AWS CDK配置数组/嵌套对象的API网关验证模型?
如何用AWS CDK配置包含数组和嵌套对象的API网关验证模型
你已经在AWS控制台中验证过以下JSON Schema模型可以正常工作:
{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "MainModel", "type": "object", "properties": { "OutterField": { "type": "array", "items": { "type": "object", "properties": { "Firstfield": { "type": "string" }, "Secondfield": { "type": "string" }, }, "required": ["Firstfield", "Secondfield"], "additionalProperties": false, "uniqueItems": true } } }, "required": ["OutterField"], "additionalProperties": false }
对应的AWS CDK代码需要严格匹配上述Schema的层级结构,以下是修正后的完整实现:
model = api.add_model("model", content_type="application/json", model_name="MainModel", schema=apigw.JsonSchema( schema=apigw.JsonSchemaVersion.DRAFT4, title="MainModel", type=apigw.JsonSchemaType.OBJECT, properties={ # 定义外层数组字段 "OutterField": apigw.JsonSchema( type=apigw.JsonSchemaType.ARRAY, # 配置数组元素的嵌套对象结构 items=apigw.JsonSchema( type=apigw.JsonSchemaType.OBJECT, properties={ "Firstfield": apigw.JsonSchema(type=apigw.JsonSchemaType.STRING), "Secondfield": apigw.JsonSchema(type=apigw.JsonSchemaType.STRING) }, required=["Firstfield", "Secondfield"], additional_properties=False, unique_items=True ) ) }, required=["OutterField"], additional_properties=False ) )
关键调整说明
- 将
Firstfield和Secondfield嵌套到OutterField数组的items对象中,完全对应原Schema的层级关系 - 通过
type=apigw.JsonSchemaType.ARRAY声明字段为数组类型,用items定义数组元素的结构 - 保留原Schema中的
required、additional_properties、unique_items等约束规则
内容的提问来源于stack exchange,提问作者user37649
相关产品推荐
相关产品推荐

