Search code examples
amazon-web-servicesaws-api-gatewayserverless-framework

AWS API Gateway Responses via serverless framework


I'd like to be able to configure API Gateway Responses via serverless framework...

This is what I want to configure

This is what my serverless.yml looks like:

#Deploy an api gateway with custom responses.
---
service: test-apigw
frameworkVersion: ">=3.20"

provider:
  name: aws
  stage: dev
  region: us-east-1
  stackName: ${self:service}
  apiName: test-apigw
  endpointType: REGIONAL 

functions: 
  hello: 
    handler: handler.endpoint
    events: 
      - http:
          path: /hello-world
          method: ANY
          private: true

package:
  individually: true
  excludeDevDependencies: false

Now I read somewhere that one can configure resources in a serverless file, however by using CFN code I'd need the ARN or the Ref of an already deployed API Gateway or, declare the API Gateway with CFN code (which I want to avoid)...

Is there a way to configure these Gateway Responses (not integration responses!!) using the same api gateway that my serverless.yml is deploying? i.e. the one with name test-apigw?


Solution

  • It turns out the response I quoted actually works for me. In the same serverless.yml file, put the GatewayResponses you want to configure.

    resources:
      Resources:
        Unauthorized:
          Type: "AWS::ApiGateway::GatewayResponse"
          Properties:
            ResponseParameters:
              gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
              gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
            ResponseTemplates:
              "application/json": ${file(gateway-responses/responses.js):unauthorized}
            ResponseType: UNAUTHORIZED
            RestApiId: !Ref ApiGatewayRestApi
            StatusCode: '401'
    

    At least for version 3.20 of serverless framework, the created API name is ApiGatewayRestApi, this will only work of course, if you're only creating one API Gw in that file and I believe, the API Gateway has to be already deployed.

    The correct way to do this is, as the official serverless documentation states, to create the API Gateway with Cloudformation code.