Skip to content

Instantly share code, notes, and snippets.

@cam8001
Last active March 4, 2022 02:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cam8001/1304705aa013a48719ecc3ff253aa981 to your computer and use it in GitHub Desktop.
Save cam8001/1304705aa013a48719ecc3ff253aa981 to your computer and use it in GitHub Desktop.
Example SAM template for API Gateway with Lambda proxy integration
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Globals:
Api:
EndpointConfiguration: REGIONAL
# Your CORS hosts need to be in this format - note the two layers of quotes.
Cors: "'*'"
# Our Python callback
Resources:
YourFunction:
Type: AWS::Serverless::Function
Properties:
Handler: callbackcode.handler
Runtime: python3.7
CodeUri: ./yourfunction/
Events:
Callback:
Type: Api
Properties:
Path: /yourcallback
Method: get
RestApiId:
Ref: YourAPIGateway
# Our callback API
YourAPIGateway:
Type: AWS::Serverless::Api
DependsOn: YourFunction
Properties:
StageName: prod
DefinitionBody:
swagger: 2.0
info:
version: "1.0"
title: "A nice title"
basePath: /prod
schemes:
- "https"
paths:
/callback:
get:
responses: {}
x-amazon-apigateway-integration:
uri:
# You need to build up the ARN with this pattern - you can't just use a !Ref or !GetAtt AFAIK.
Fn::Sub: arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${YourFunction.Arn}/invocations
passthroughBehavior: "when_no_match"
httpMethod: "POST"
type: "aws_proxy"
import json
import os
def handler(event, context):
body = 'foo'
# Now, send a 200 and include our event details.
response = {
'statusCode': 200,
'body': body
}
# Ensure that this function can be called from wherever you want to (CORS headers).
response["headers"] = {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
# Return our response object.
return response
@cam8001
Copy link
Author

cam8001 commented Dec 2, 2019

I got caught up on the CORS definition for quite a while. My deploys were failing and I was getting an inscrutable (to me) message:

Errors found during import: Unable to put integration response on 'OPTIONS' for resource at path '/callback': Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: *]

I found on another gist someone mentioned debugging with sam local start-api --debug, which helped a lot! So, try that if your template fails, it may help track it down.

@zcmgyu
Copy link

zcmgyu commented Apr 12, 2021

@cam8001
Remember 2 quotes

Cors: "'*'"

@JesusDavidOC
Copy link

JesusDavidOC commented Apr 29, 2021

I have a question, how to set a response in 'responses' key?

paths:
/callback:
get:
responses: {#here}
x-amazon-apigateway-integration:
uri:

I only write the code? example: responses:{200}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment