Create methods under / using CF for API Gateway

2020-08-08 08:19发布

问题:

How do I create methods under API Gateway's root / folder using CF? So for example I have a Gateway that looks like the following:

/ OPTIONS POST

However when trying to do that with CF I get: Resource's path part only allow a-zA-Z0-9._- and curly braces at the beginning and the end. So my PathPart is the offending line.

  ApiGate:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt 
        - ApiGateApi
        - RootResourceId
      PathPart: '{/}'
      RestApiId: !Ref ApiGateApi

I can change the PathPart to something else but then it creates it as a child object under / which is what I don't want.

回答1:

Turns out after adding the following to my AWS::ApiGateway::Method it works now.

  MyMethodOPTIONS:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      ResourceId: !GetAtt MyRestApi.RootResourceId

Here is more context into my Template:

  ApiGatewayMethodOPTIONS:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      ResourceId: !GetAtt ApiGatewayRestApi.RootResourceId
      RestApiId: !Ref ApiGatewayRestApi
      AuthorizationType: NONE
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            ResponseTemplates:
              application/json: ''
            StatusCode: '200'
        PassthroughBehavior: NEVER
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: '200'
  ApiGatewayRestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      ApiKeySourceType: HEADER
      EndpointConfiguration:
        Types:
          - REGIONAL
      Name: SearchAPI


回答2:

This fixes my problem, in my case I needed to have 2 methods: 1. will respond to requests to root e.g. https://<api-url>/prod or https://<api-url>/prod/. This will use the RootResourceId of the API Gateway:

ResourceId: !GetAtt myApiGateway.RootResourceId

  1. this will respond to requests to whatever has been set under https://<api-url>/prod/. Could be petstore or if using {proxy+} then the backend workload will try to resolve the request. It will refer to the Resource type defined in the template:

ResourceId: !Ref myResource