Resource

class aws_cdk.aws_apigateway.Resource(scope, id, *, parent, path_part, default_cors_preflight_options=None, default_integration=None, default_method_options=None)

Bases: ResourceBase

ExampleMetadata:

infused

Example:

# books_backend: apigateway.LambdaIntegration

api = apigateway.RestApi(self, "books",
    default_integration=books_backend
)

books = api.root.add_resource("books")
books.add_method("GET") # integrated with `booksBackend`
books.add_method("POST") # integrated with `booksBackend`

book = books.add_resource("{book_id}")
book.add_method("GET")
Parameters:
  • scope (Construct) –

  • id (str) –

  • parent (IResource) – The parent resource of this resource. You can either pass another Resource object or a RestApi object here.

  • path_part (str) – A path name for the resource.

  • default_cors_preflight_options (Union[CorsOptions, Dict[str, Any], None]) – Adds a CORS preflight OPTIONS method to this resource and all child resources. You can add CORS at the resource-level using addCorsPreflight. Default: - CORS is disabled

  • default_integration (Optional[Integration]) – An integration to use as a default for all methods created within this API unless an integration is specified. Default: - Inherited from parent.

  • default_method_options (Union[MethodOptions, Dict[str, Any], None]) – Method options to use as a default for all methods created within this API unless custom options are specified. Default: - Inherited from parent.

Methods

add_cors_preflight(*, allow_origins, allow_credentials=None, allow_headers=None, allow_methods=None, disable_cache=None, expose_headers=None, max_age=None, status_code=None)

Adds an OPTIONS method to this resource which responds to Cross-Origin Resource Sharing (CORS) preflight requests.

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

Parameters:
  • allow_origins (Sequence[str]) – Specifies the list of origins that are allowed to make requests to this resource. If you wish to allow all origins, specify Cors.ALL_ORIGINS or [ * ]. Responses will include the Access-Control-Allow-Origin response header. If Cors.ALL_ORIGINS is specified, the Vary: Origin response header will also be included.

  • allow_credentials (Optional[bool]) – The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to frontend JavaScript code when the request’s credentials mode (Request.credentials) is “include”. When a request’s credentials mode (Request.credentials) is “include”, browsers will only expose the response to frontend JavaScript code if the Access-Control-Allow-Credentials value is true. Credentials are cookies, authorization headers or TLS client certificates. Default: false

  • allow_headers (Optional[Sequence[str]]) – The Access-Control-Allow-Headers response header is used in response to a preflight request which includes the Access-Control-Request-Headers to indicate which HTTP headers can be used during the actual request. Default: Cors.DEFAULT_HEADERS

  • allow_methods (Optional[Sequence[str]]) – The Access-Control-Allow-Methods response header specifies the method or methods allowed when accessing the resource in response to a preflight request. If ANY is specified, it will be expanded to Cors.ALL_METHODS. Default: Cors.ALL_METHODS

  • disable_cache (Optional[bool]) – Sets Access-Control-Max-Age to -1, which means that caching is disabled. This option cannot be used with maxAge. Default: - cache is enabled

  • expose_headers (Optional[Sequence[str]]) – The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names. If you want clients to be able to access other headers, you have to list them using the Access-Control-Expose-Headers header. Default: - only the 6 CORS-safelisted response headers are exposed: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma

  • max_age (Optional[Duration]) – The Access-Control-Max-Age response header indicates how long the results of a preflight request (that is the information contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached. To disable caching altogether use disableCache: true. Default: - browser-specific (see reference)

  • status_code (Union[int, float, None]) – Specifies the response status code returned from the OPTIONS method. Default: 204

Return type:

Method

add_method(http_method, integration=None, *, api_key_required=None, authorization_scopes=None, authorization_type=None, authorizer=None, method_responses=None, operation_name=None, request_models=None, request_parameters=None, request_validator=None, request_validator_options=None)

Defines a new method for this resource.

Parameters:
  • http_method (str) –

  • integration (Optional[Integration]) –

  • api_key_required (Optional[bool]) – Indicates whether the method requires clients to submit a valid API key. Default: false

  • authorization_scopes (Optional[Sequence[str]]) – A list of authorization scopes configured on the method. The scopes are used with a COGNITO_USER_POOLS authorizer to authorize the method invocation. Default: - no authorization scopes

  • authorization_type (Optional[AuthorizationType]) – Method authorization. If the value is set of Custom, an authorizer must also be specified. If you’re using one of the authorizers that are available via the Authorizer class, such as Authorizer#token(), it is recommended that this option not be specified. The authorizer will take care of setting the correct authorization type. However, specifying an authorization type using this property that conflicts with what is expected by the Authorizer will result in an error. Default: - open access unless authorizer is specified

  • authorizer (Optional[IAuthorizer]) – If authorizationType is Custom, this specifies the ID of the method authorizer resource. If specified, the value of authorizationType must be set to Custom

  • method_responses (Optional[Sequence[Union[MethodResponse, Dict[str, Any]]]]) – The responses that can be sent to the client who calls the method. Default: None This property is not required, but if these are not supplied for a Lambda proxy integration, the Lambda function must return a value of the correct format, for the integration response to be correctly mapped to a response to the client.

  • operation_name (Optional[str]) – A friendly operation name for the method. For example, you can assign the OperationName of ListPets for the GET /pets method.

  • request_models (Optional[Mapping[str, IModel]]) – The models which describe data structure of request payload. When combined with requestValidator or requestValidatorOptions, the service will validate the API request payload before it reaches the API’s Integration (including proxies). Specify requestModels as key-value pairs, with a content type (e.g. 'application/json') as the key and an API Gateway Model as the value.

  • request_parameters (Optional[Mapping[str, bool]]) – The request parameters that API Gateway accepts. Specify request parameters as key-value pairs (string-to-Boolean mapping), with a source as the key and a Boolean as the value. The Boolean specifies whether a parameter is required. A source must match the format method.request.location.name, where the location is querystring, path, or header, and name is a valid, unique parameter name. Default: None

  • request_validator (Optional[IRequestValidator]) – The ID of the associated request validator. Only one of requestValidator or requestValidatorOptions must be specified. Works together with requestModels or requestParameters to validate the request before it reaches integration like Lambda Proxy Integration. Default: - No default validator

  • request_validator_options (Union[RequestValidatorOptions, Dict[str, Any], None]) – Request validator options to create new validator Only one of requestValidator or requestValidatorOptions must be specified. Works together with requestModels or requestParameters to validate the request before it reaches integration like Lambda Proxy Integration. Default: - No default validator

Return type:

Method

add_proxy(*, any_method=None, default_cors_preflight_options=None, default_integration=None, default_method_options=None)

Adds a greedy proxy resource (“{proxy+}”) and an ANY method to this route.

Parameters:
  • any_method (Optional[bool]) – Adds an “ANY” method to this resource. If set to false, you will have to explicitly add methods to this resource after it’s created. Default: true

  • default_cors_preflight_options (Union[CorsOptions, Dict[str, Any], None]) – Adds a CORS preflight OPTIONS method to this resource and all child resources. You can add CORS at the resource-level using addCorsPreflight. Default: - CORS is disabled

  • default_integration (Optional[Integration]) – An integration to use as a default for all methods created within this API unless an integration is specified. Default: - Inherited from parent.

  • default_method_options (Union[MethodOptions, Dict[str, Any], None]) – Method options to use as a default for all methods created within this API unless custom options are specified. Default: - Inherited from parent.

Return type:

ProxyResource

add_resource(path_part, *, default_cors_preflight_options=None, default_integration=None, default_method_options=None)

Defines a new child resource where this resource is the parent.

Parameters:
  • path_part (str) –

  • default_cors_preflight_options (Union[CorsOptions, Dict[str, Any], None]) – Adds a CORS preflight OPTIONS method to this resource and all child resources. You can add CORS at the resource-level using addCorsPreflight. Default: - CORS is disabled

  • default_integration (Optional[Integration]) – An integration to use as a default for all methods created within this API unless an integration is specified. Default: - Inherited from parent.

  • default_method_options (Union[MethodOptions, Dict[str, Any], None]) – Method options to use as a default for all methods created within this API unless custom options are specified. Default: - Inherited from parent.

Return type:

Resource

apply_removal_policy(policy)

Apply the given removal policy to this resource.

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).

Parameters:

policy (RemovalPolicy) –

Return type:

None

get_resource(path_part)

Retrieves a child resource by path part.

Parameters:

path_part (str) –

Return type:

Optional[IResource]

resource_for_path(path)

Gets or create all resources leading up to the specified path.

  • Path may only start with “/” if this method is called on the root resource.

  • All resources are created using default options.

Parameters:

path (str) –

Return type:

Resource

to_string()

Returns a string representation of this construct.

Return type:

str

Attributes

api

The rest API that this resource is part of.

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 it’s hash to determine the ID of the deployment. This allows us to automatically update the deployment when the model of the REST API changes.

default_cors_preflight_options

Default options for CORS preflight OPTIONS method.

default_integration

An integration to use as a default for all methods created within this API unless an integration is specified.

default_method_options

Method options to use as a default for all methods created within this API unless custom options are specified.

env

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.

node

The tree node.

parent_resource

The parent of this resource or undefined for the root resource.

path

The full path of this resource.

resource_id

The ID of the resource.

stack

The stack in which this resource is defined.

Static Methods

classmethod from_resource_attributes(scope, id, *, path, resource_id, rest_api)

Import an existing resource.

Parameters:
  • scope (Construct) –

  • id (str) –

  • path (str) – The full path of this resource.

  • resource_id (str) – The ID of the resource.

  • rest_api (IRestApi) – The rest API that this resource is part of.

Return type:

IResource

classmethod is_construct(x)

Checks if x is a construct.

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:

x (Any) – Any object.

Return type:

bool

Returns:

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

classmethod is_owned_resource(construct)

Returns true if the construct was created by CDK, and false otherwise.

Parameters:

construct (IConstruct) –

Return type:

bool

classmethod is_resource(construct)

Check whether the given construct is a Resource.

Parameters:

construct (IConstruct) –

Return type:

bool