2

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Very valuable info. Exactly what I was looking for: allowing HTTP 401 responses from API Gateway to be caught sensibly in the browser without stumbling over nonsensical CORS errors -- and doing so via Serverless YAML. ...that said, it's stuff like this that makes me regret going the Serverless route. Very convenient at first, until you hit all these little hidden pitfalls that the Serverless creators seem to have never even thought of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.