Customized response example for Amazon SAM - Amazon Serverless Application Model
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Customized response example for Amazon SAM

You can customize some API Gateway error responses by defining response headers within your Amazon SAM template. To do this, you use the Gateway Response Object data type.

The following is an example Amazon SAM template that creates a customized response for the DEFAULT_5XX error.

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: MyApi: Type: AWS::Serverless::Api Properties: StageName: Prod GatewayResponses: DEFAULT_5XX: ResponseParameters: Headers: Access-Control-Expose-Headers: "'WWW-Authenticate'" Access-Control-Allow-Origin: "'*'" ErrorHeader: "'MyCustomErrorHeader'" ResponseTemplates: application/json: "{\"message\": \"Error on the $context.resourcePath resource\" }" GetFunction: Type: AWS::Serverless::Function Properties: Runtime: python3.10 Handler: index.handler InlineCode: | def handler(event, context): raise Exception('Check out the new response!') Events: GetResource: Type: Api Properties: Path: /error Method: get RestApiId: !Ref MyApi

For more information about API Gateway responses, see Gateway responses in API Gateway in the API Gateway Developer Guide.