You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python CDK为AWS API Gateway配置200响应体(application/json)

Python CDK 配置API Gateway 200状态码响应属性

要实现控制台中配置的「200状态码响应、内容类型application/json、模型为空」的效果,直接通过CDK的MethodResponse配置即可,以下是完整示例代码:

代码实现

from aws_cdk import (
    aws_apigateway as apigateway,
    Stack,
    RemovalPolicy,
)
from constructs import Construct

class ApiGatewayDemoStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # 创建RestApi实例
        demo_api = apigateway.RestApi(
            self, "DemoApi",
            rest_api_name="Demo API",
            removal_policy=RemovalPolicy.DESTROY
        )

        # 添加API资源(示例为根路径下的/hello)
        hello_resource = demo_api.root.add_resource("hello")

        # 添加GET方法(这里用Mock集成做演示,可替换为Lambda等实际集成)
        get_hello_method = hello_resource.add_method(
            "GET",
            apigateway.MockIntegration(
                integration_responses=[
                    apigateway.IntegrationResponse(
                        status_code="200",
                        response_templates={"application/json": '{"msg": "hello"}'}
                    )
                ],
                passthrough_behavior=apigateway.PassthroughBehavior.NEVER,
                request_templates={"application/json": '{"statusCode": 200}'}
            )
        )

        # 配置200状态码的响应属性
        get_hello_method.add_method_response(
            status_code="200",
            # 指定内容类型为application/json,模型为空(用EmptyModel实现)
            response_models={"application/json": apigateway.EmptyModel()},
            # 确保返回Content-Type响应头
            response_parameters={"method.response.header.Content-Type": True}
        )

关键说明

  • add_method_response:定义API对外暴露的响应规则,对应控制台中「响应」标签页的配置
  • response_models:通过apigateway.EmptyModel()实现「模型为空」的要求,同时绑定application/json内容类型
  • response_parameters:开启Content-Type头的返回,确保客户端收到正确的响应类型
  • 集成部分的IntegrationResponse是后端到API Gateway的响应配置,根据实际后端类型调整(比如Lambda集成无需Mock相关配置)

内容的提问来源于stack exchange,提问作者newbiee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:27:18