Skip to content
v2.274.0

Model L2 construct ​

Example ​

ts
declare const api: apigateway.RestApi;

// We define the JSON Schema for the transformed valid response
const responseModel = api.addModel('ResponseModel', {
  contentType: 'application/json',
  modelName: 'ResponseModel',
  schema: {
    schema: apigateway.JsonSchemaVersion.DRAFT4,
    title: 'pollResponse',
    type: apigateway.JsonSchemaType.OBJECT,
    properties: {
      state: { type: apigateway.JsonSchemaType.STRING },
      greeting: { type: apigateway.JsonSchemaType.STRING }
    }
  }
});

// We define the JSON Schema for the transformed error response
const errorResponseModel = api.addModel('ErrorResponseModel', {
  contentType: 'application/json',
  modelName: 'ErrorResponseModel',
  schema: {
    schema: apigateway.JsonSchemaVersion.DRAFT4,
    title: 'errorResponse',
    type: apigateway.JsonSchemaType.OBJECT,
    properties: {
      state: { type: apigateway.JsonSchemaType.STRING },
      message: { type: apigateway.JsonSchemaType.STRING }
    }
  }
});
python
# api: apigateway.RestApi


# We define the JSON Schema for the transformed valid response
response_model = api.add_model("ResponseModel",
    content_type="application/json",
    model_name="ResponseModel",
    schema=apigateway.JsonSchema(
        schema=apigateway.JsonSchemaVersion.DRAFT4,
        title="pollResponse",
        type=apigateway.JsonSchemaType.OBJECT,
        properties={
            "state": apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING),
            "greeting": apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING)
        }
    )
)

# We define the JSON Schema for the transformed error response
error_response_model = api.add_model("ErrorResponseModel",
    content_type="application/json",
    model_name="ErrorResponseModel",
    schema=apigateway.JsonSchema(
        schema=apigateway.JsonSchemaVersion.DRAFT4,
        title="errorResponse",
        type=apigateway.JsonSchemaType.OBJECT,
        properties={
            "state": apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING),
            "message": apigateway.JsonSchema(type=apigateway.JsonSchemaType.STRING)
        }
    )
)
java
RestApi api;


// We define the JSON Schema for the transformed valid response
Model responseModel = api.addModel("ResponseModel", ModelOptions.builder()
        .contentType("application/json")
        .modelName("ResponseModel")
        .schema(JsonSchema.builder()
                .schema(JsonSchemaVersion.DRAFT4)
                .title("pollResponse")
                .type(JsonSchemaType.OBJECT)
                .properties(Map.of(
                        "state", JsonSchema.builder().type(JsonSchemaType.STRING).build(),
                        "greeting", JsonSchema.builder().type(JsonSchemaType.STRING).build()))
                .build())
        .build());

// We define the JSON Schema for the transformed error response
Model errorResponseModel = api.addModel("ErrorResponseModel", ModelOptions.builder()
        .contentType("application/json")
        .modelName("ErrorResponseModel")
        .schema(JsonSchema.builder()
                .schema(JsonSchemaVersion.DRAFT4)
                .title("errorResponse")
                .type(JsonSchemaType.OBJECT)
                .properties(Map.of(
                        "state", JsonSchema.builder().type(JsonSchemaType.STRING).build(),
                        "message", JsonSchema.builder().type(JsonSchemaType.STRING).build()))
                .build())
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
RestApi api;


// We define the JSON Schema for the transformed valid response
var responseModel = api.AddModel("ResponseModel", new ModelOptions {
    ContentType = "application/json",
    ModelName = "ResponseModel",
    Schema = new JsonSchema {
        Schema = JsonSchemaVersion.DRAFT4,
        Title = "pollResponse",
        Type = JsonSchemaType.OBJECT,
        Properties = new Dictionary<string, JsonSchema> {
            { "state", new JsonSchema { Type = JsonSchemaType.STRING } },
            { "greeting", new JsonSchema { Type = JsonSchemaType.STRING } }
        }
    }
});

// We define the JSON Schema for the transformed error response
var errorResponseModel = api.AddModel("ErrorResponseModel", new ModelOptions {
    ContentType = "application/json",
    ModelName = "ErrorResponseModel",
    Schema = new JsonSchema {
        Schema = JsonSchemaVersion.DRAFT4,
        Title = "errorResponse",
        Type = JsonSchemaType.OBJECT,
        Properties = new Dictionary<string, JsonSchema> {
            { "state", new JsonSchema { Type = JsonSchemaType.STRING } },
            { "message", new JsonSchema { Type = JsonSchemaType.STRING } }
        }
    }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var api RestApi


// We define the JSON Schema for the transformed valid response
responseModel := api.AddModel(jsii.String("ResponseModel"), &ModelOptions{
	ContentType: jsii.String("application/json"),
	ModelName: jsii.String("ResponseModel"),
	Schema: &JsonSchema{
		Schema: apigateway.JsonSchemaVersion_DRAFT4,
		Title: jsii.String("pollResponse"),
		Type: apigateway.JsonSchemaType_OBJECT,
		Properties: map[string]JsonSchema{
			"state": &JsonSchema{
				"type": apigateway.JsonSchemaType_STRING,
			},
			"greeting": &JsonSchema{
				"type": apigateway.JsonSchemaType_STRING,
			},
		},
	},
})

// We define the JSON Schema for the transformed error response
errorResponseModel := api.AddModel(jsii.String("ErrorResponseModel"), &ModelOptions{
	ContentType: jsii.String("application/json"),
	ModelName: jsii.String("ErrorResponseModel"),
	Schema: &JsonSchema{
		Schema: apigateway.JsonSchemaVersion_DRAFT4,
		Title: jsii.String("errorResponse"),
		Type: apigateway.JsonSchemaType_OBJECT,
		Properties: map[string]JsonSchema{
			"state": &JsonSchema{
				"type": apigateway.JsonSchemaType_STRING,
			},
			"message": &JsonSchema{
				"type": apigateway.JsonSchemaType_STRING,
			},
		},
	},
})

Initializer ​

ts
new Model(scope: Construct, id: string, props: ModelProps)
python
Model(scope: Construct, id: str, props: ModelProps)
java
new Model(Construct scope, String id, ModelProps props)
csharp
new Model(Construct scope, string id, ModelProps props)
go
NewModel(Scope Construct, Id *string, Props ModelProps)

Construct Props ​

contentTypestringcontent_typestrcontentTypeStringContentTypestringContentType*string= 'application/json'#
The content type for the model.

You can also force a content type in the request or response model mapping.

descriptionstringdescriptionstrdescriptionStringDescriptionstringDescription*string= None#
A description that identifies this model.
modelNamestringmodel_namestrmodelNameStringModelNamestringModelName*string= <auto> If you don't specify a na…#
A name for the model.

Important If you specify a name, you cannot perform updates that require replacement of this resource. You can perform updates that require no or some interruption. If you must replace the resource, specify a new name.

default

Default: <auto> If you don't specify a name, AWS CloudFormation generates a unique physical ID and uses that ID for the model name. For more information, see Name Type.

restApiIRestApirest_apiIRestApirestApiIRestApiRestApiIRestApiRestApiIRestApirequired#
The rest API that this model is part of.
notes

The reason we need the RestApi object itself and not just the ID is because the model is being tracked by the top-level RestApi object for the purpose of calculating its hash to determine the ID of the deployment. This allows us to automatically update the deployment when the model of the REST API changes.

schemaJsonSchemaschemaJsonSchemaschemaJsonSchemaSchemaJsonSchemaSchemaJsonSchemarequired#
The schema to use to transform data to one or more output formats.

Specify null ({}) if you don't want to specify a schema.

Properties ​

EMPTY_MODELIModelempty_modelIModelEMPTY_MODELIModelEMPTY_MODELIModelEMPTY_MODELIModelrequiredstatic#
Represents a reference to a REST API's Empty model, which is available as part of the model collection by default.
notes

This can be used for mapping JSON responses from an integration to what is returned to a client, where strong typing is not required. In the absence of any defined model, the Empty model will be used to return the response payload unmapped.

Definition { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "Empty Schema", "type" : "object" }

The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

ERROR_MODELIModelerror_modelIModelERROR_MODELIModelERROR_MODELIModelERROR_MODELIModelrequiredstatic#
Represents a reference to a REST API's Error model, which is available as part of the model collection by default.
notes

This can be used for mapping error JSON responses from an integration to a client, where a simple generic message field is sufficient to map and return an error payload.

Definition { "$schema" : "http://json-schema.org/draft-04/schema#", "title" : "Error Schema", "type" : "object", "properties" : { "message" : { "type" : "string" } } }

modelIdstringmodel_idstrmodelIdStringModelIdstringModelId*stringrequired#
Returns the model name, such as 'myModel'.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromModelName(scope: Construct, id: string, modelName: string): IModel@staticmethod def from_model_name(scope: Construct, id: str, model_name: str) -> IModelpublic static IModel fromModelName(Construct scope, String id, String modelName)public static IModel FromModelName(Construct scope, string id, string modelName)func FromModelName(Scope Construct, Id *string, ModelName *string) IModelstatic#
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.