Skip to content
v2.274.0

MockIntegration Class ​

This type of integration lets API Gateway return a response without sending the request further to the backend.

This is useful for API testing because it can be used to test the integration set up without incurring charges for using the backend and to enable collaborative development of an API. In collaborative development, a team can isolate their development effort by setting up simulations of API components owned by other teams by using the MOCK integrations. It is also used to return CORS-related headers to ensure that the API method permits CORS access. In fact, the API Gateway console integrates the OPTIONS method to support CORS with a mock integration. Gateway responses are other examples of mock integrations.

Example ​

ts
import * as path from 'path';
import * as lambda from '../../../aws-lambda';
import { App, Stack } from '../../../core';
import { MockIntegration, PassthroughBehavior, RestApi, RequestAuthorizer, IdentitySource } from '../../lib';

// Against the RestApi endpoint from the stack output, run
// `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>?allow=yes` should return 403
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>?allow=yes` should return 200

const app = new App();
const stack = new Stack(app, 'RequestAuthorizerInteg');

const authorizerFn = new lambda.Function(stack, 'MyAuthorizerFunction', {
  runtime: lambda.Runtime.NODEJS_LATEST,
  handler: 'index.handler',
  code: lambda.AssetCode.fromAsset(path.join(__dirname, 'integ.request-authorizer.handler')),
});

const restapi = new RestApi(stack, 'MyRestApi', { cloudWatchRole: true });

const authorizer = new RequestAuthorizer(stack, 'MyAuthorizer', {
  handler: authorizerFn,
  identitySources: [IdentitySource.header('Authorization'), IdentitySource.queryString('allow')],
});

const secondAuthorizer = new RequestAuthorizer(stack, 'MySecondAuthorizer', {
  handler: authorizerFn,
  identitySources: [IdentitySource.header('Authorization'), IdentitySource.queryString('allow')],
});

restapi.root.addMethod('ANY', new MockIntegration({
  integrationResponses: [
    { statusCode: '200' },
  ],
  passthroughBehavior: PassthroughBehavior.NEVER,
  requestTemplates: {
    'application/json': '{ "statusCode": 200 }',
  },
}), {
  methodResponses: [
    { statusCode: '200' },
  ],
  authorizer,
});

restapi.root.resourceForPath('auth').addMethod('ANY', new MockIntegration({
  integrationResponses: [
    { statusCode: '200' },
  ],
  passthroughBehavior: PassthroughBehavior.NEVER,
  requestTemplates: {
    'application/json': '{ "statusCode": 200 }',
  },
}), {
  methodResponses: [
    { statusCode: '200' },
  ],
  authorizer: secondAuthorizer,
});
python
from aws_cdk.aws_apigateway import IntegrationResponse, MethodResponse, IntegrationResponse, MethodResponse
import path as path
import aws_cdk.aws_lambda as lambda_
from aws_cdk import App, Stack
from aws_cdk.aws_apigateway import MockIntegration, PassthroughBehavior, RestApi, RequestAuthorizer, IdentitySource

# Against the RestApi endpoint from the stack output, run
# `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401
# `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>?allow=yes` should return 403
# `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>?allow=yes` should return 200

app = App()
stack = Stack(app, "RequestAuthorizerInteg")

authorizer_fn = lambda_.Function(stack, "MyAuthorizerFunction",
    runtime=lambda_.Runtime.NODEJS_LATEST,
    handler="index.handler",
    code=lambda_.AssetCode.from_asset(path.join(__dirname, "integ.request-authorizer.handler"))
)

restapi = RestApi(stack, "MyRestApi", cloud_watch_role=True)

authorizer = RequestAuthorizer(stack, "MyAuthorizer",
    handler=authorizer_fn,
    identity_sources=[IdentitySource.header("Authorization"), IdentitySource.query_string("allow")]
)

second_authorizer = RequestAuthorizer(stack, "MySecondAuthorizer",
    handler=authorizer_fn,
    identity_sources=[IdentitySource.header("Authorization"), IdentitySource.query_string("allow")]
)

restapi.root.add_method("ANY", MockIntegration(
    integration_responses=[IntegrationResponse(status_code="200")
    ],
    passthrough_behavior=PassthroughBehavior.NEVER,
    request_templates={
        "application/json": "{ \"statusCode\": 200 }"
    }
),
    method_responses=[MethodResponse(status_code="200")
    ],
    authorizer=authorizer
)

restapi.root.resource_for_path("auth").add_method("ANY", MockIntegration(
    integration_responses=[IntegrationResponse(status_code="200")
    ],
    passthrough_behavior=PassthroughBehavior.NEVER,
    request_templates={
        "application/json": "{ \"statusCode\": 200 }"
    }
),
    method_responses=[MethodResponse(status_code="200")
    ],
    authorizer=second_authorizer
)
java
import path.*;
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.services.apigateway.MockIntegration;
import software.amazon.awscdk.services.apigateway.PassthroughBehavior;
import software.amazon.awscdk.services.apigateway.RestApi;
import software.amazon.awscdk.services.apigateway.RequestAuthorizer;
import software.amazon.awscdk.services.apigateway.IdentitySource;

// Against the RestApi endpoint from the stack output, run
// `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>?allow=yes` should return 403
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>?allow=yes` should return 200

App app = new App();
Stack stack = new Stack(app, "RequestAuthorizerInteg");

Function authorizerFn = Function.Builder.create(stack, "MyAuthorizerFunction")
        .runtime(Runtime.NODEJS_LATEST)
        .handler("index.handler")
        .code(AssetCode.fromAsset(join(__dirname, "integ.request-authorizer.handler")))
        .build();

RestApi restapi = RestApi.Builder.create(stack, "MyRestApi").cloudWatchRole(true).build();

RequestAuthorizer authorizer = RequestAuthorizer.Builder.create(stack, "MyAuthorizer")
        .handler(authorizerFn)
        .identitySources(List.of(IdentitySource.header("Authorization"), IdentitySource.queryString("allow")))
        .build();

RequestAuthorizer secondAuthorizer = RequestAuthorizer.Builder.create(stack, "MySecondAuthorizer")
        .handler(authorizerFn)
        .identitySources(List.of(IdentitySource.header("Authorization"), IdentitySource.queryString("allow")))
        .build();

restapi.root.addMethod("ANY", MockIntegration.Builder.create()
        .integrationResponses(List.of(IntegrationResponse.builder().statusCode("200").build()))
        .passthroughBehavior(PassthroughBehavior.NEVER)
        .requestTemplates(Map.of(
                "application/json", "{ \"statusCode\": 200 }"))
        .build(), MethodOptions.builder()
        .methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
        .authorizer(authorizer)
        .build());

restapi.root.resourceForPath("auth").addMethod("ANY", MockIntegration.Builder.create()
        .integrationResponses(List.of(IntegrationResponse.builder().statusCode("200").build()))
        .passthroughBehavior(PassthroughBehavior.NEVER)
        .requestTemplates(Map.of(
                "application/json", "{ \"statusCode\": 200 }"))
        .build(), MethodOptions.builder()
        .methodResponses(List.of(MethodResponse.builder().statusCode("200").build()))
        .authorizer(secondAuthorizer)
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Path;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;

// Against the RestApi endpoint from the stack output, run
// `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>?allow=yes` should return 403
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>?allow=yes` should return 200

var app = new App();
var stack = new Stack(app, "RequestAuthorizerInteg");

var authorizerFn = new Function(stack, "MyAuthorizerFunction", new FunctionProps {
    Runtime = Runtime.NODEJS_LATEST,
    Handler = "index.handler",
    Code = AssetCode.FromAsset(Join(__dirname, "integ.request-authorizer.handler"))
});

var restapi = new RestApi(stack, "MyRestApi", new RestApiProps { CloudWatchRole = true });

var authorizer = new RequestAuthorizer(stack, "MyAuthorizer", new RequestAuthorizerProps {
    Handler = authorizerFn,
    IdentitySources = new [] { IdentitySource.Header("Authorization"), IdentitySource.QueryString("allow") }
});

var secondAuthorizer = new RequestAuthorizer(stack, "MySecondAuthorizer", new RequestAuthorizerProps {
    Handler = authorizerFn,
    IdentitySources = new [] { IdentitySource.Header("Authorization"), IdentitySource.QueryString("allow") }
});

restapi.Root.AddMethod("ANY", new MockIntegration(new IntegrationOptions {
    IntegrationResponses = new [] { new IntegrationResponse { StatusCode = "200" } },
    PassthroughBehavior = PassthroughBehavior.NEVER,
    RequestTemplates = new Dictionary<string, string> {
        { "application/json", "{ \"statusCode\": 200 }" }
    }
}), new MethodOptions {
    MethodResponses = new [] { new MethodResponse { StatusCode = "200" } },
    Authorizer = authorizer
});

restapi.Root.ResourceForPath("auth").AddMethod("ANY", new MockIntegration(new IntegrationOptions {
    IntegrationResponses = new [] { new IntegrationResponse { StatusCode = "200" } },
    PassthroughBehavior = PassthroughBehavior.NEVER,
    RequestTemplates = new Dictionary<string, string> {
        { "application/json", "{ \"statusCode\": 200 }" }
    }
}), new MethodOptions {
    MethodResponses = new [] { new MethodResponse { StatusCode = "200" } },
    Authorizer = secondAuthorizer
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import path "github.com/aws-samples/dummy/path"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"

// Against the RestApi endpoint from the stack output, run
// `curl -s -o /dev/null -w "%{http_code}" <url>` should return 401
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: deny' <url>?allow=yes` should return 403
// `curl -s -o /dev/null -w "%{http_code}" -H 'Authorization: allow' <url>?allow=yes` should return 200

app := awscdk.NewApp()
stack := awscdk.NewStack(app, jsii.String("RequestAuthorizerInteg"))

authorizerFn := lambda.NewFunction(stack, jsii.String("MyAuthorizerFunction"), &FunctionProps{
	Runtime: lambda.Runtime_NODEJS_LATEST(),
	Handler: jsii.String("index.handler"),
	Code: lambda.AssetCode_FromAsset(path.join(__dirname, jsii.String("integ.request-authorizer.handler"))),
})

restapi := awscdk.NewRestApi(stack, jsii.String("MyRestApi"), &RestApiProps{
	CloudWatchRole: jsii.Boolean(true),
})

authorizer := awscdk.NewRequestAuthorizer(stack, jsii.String("MyAuthorizer"), &RequestAuthorizerProps{
	Handler: authorizerFn,
	IdentitySources: []*string{
		awscdk.IdentitySource_Header(jsii.String("Authorization")),
		awscdk.IdentitySource_QueryString(jsii.String("allow")),
	},
})

secondAuthorizer := awscdk.NewRequestAuthorizer(stack, jsii.String("MySecondAuthorizer"), &RequestAuthorizerProps{
	Handler: authorizerFn,
	IdentitySources: []*string{
		awscdk.IdentitySource_*Header(jsii.String("Authorization")),
		awscdk.IdentitySource_*QueryString(jsii.String("allow")),
	},
})

restapi.Root.AddMethod(jsii.String("ANY"), awscdk.NewMockIntegration(&IntegrationOptions{
	IntegrationResponses: []IntegrationResponse{
		&IntegrationResponse{
			StatusCode: jsii.String("200"),
		},
	},
	PassthroughBehavior: awscdk.PassthroughBehavior_NEVER,
	RequestTemplates: map[string]*string{
		"application/json": jsii.String("{ \"statusCode\": 200 }"),
	},
}), &MethodOptions{
	MethodResponses: []MethodResponse{
		&MethodResponse{
			StatusCode: jsii.String("200"),
		},
	},
	Authorizer: Authorizer,
})

restapi.Root.ResourceForPath(jsii.String("auth")).AddMethod(jsii.String("ANY"), awscdk.NewMockIntegration(&IntegrationOptions{
	IntegrationResponses: []IntegrationResponse{
		&IntegrationResponse{
			StatusCode: jsii.String("200"),
		},
	},
	PassthroughBehavior: awscdk.PassthroughBehavior_NEVER,
	RequestTemplates: map[string]*string{
		"application/json": jsii.String("{ \"statusCode\": 200 }"),
	},
}), &MethodOptions{
	MethodResponses: []MethodResponse{
		&MethodResponse{
			StatusCode: jsii.String("200"),
		},
	},
	Authorizer: secondAuthorizer,
})

Initializer ​

ts
new MockIntegration(options?: IntegrationOptions)
python
MockIntegration(options: typing.Optional[IntegrationOptions] = None)
java
new MockIntegration(IntegrationOptions options)
csharp
new MockIntegration(IntegrationOptions? options = null)
go
NewMockIntegration(Options IntegrationOptions)

Methods ​

bind(method: Method): IntegrationConfigdef bind(self, method: Method) -> IntegrationConfigpublic IntegrationConfig bind(Method method)public IntegrationConfig Bind(Method method)func Bind(Method Method) IntegrationConfig#
Can be overridden by subclasses to allow the integration to interact with the method being integrated, access the REST API object, method ARNs, etc.