Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an API Gateway Proxy Resource using SAM

I have an apparently-simple requirement to create a proxy resource in SAM (Amazon's Serverless Application Model). So simple in fact that Amazon's documentation appears to leave this as an exercise to the reader!

I want to create an AWS API Gateway catch-all endpoint to proxy everything to another HTTP service.

In the AWS Console, the configuration I am trying to build looks as follows:

enter image description here

I have seen this excellent post by Christian Johansen and his related Stack Overflow question here for how to do the same thing in CloudFormation. I suppose I could just use that code in SAM, however, SAM has its implicit and explicit APIs, so I want to avoid creating explicit resources if the "right way" is to refer to implicit resources.

Does anyone know how to do this?

like image 464
Alex Harvey Avatar asked Jan 27 '19 06:01

Alex Harvey


People also ask

How do I create a proxy resource in API gateway?

To set up a proxy integration in an API Gateway API with a proxy resource, you perform the following tasks: Create a proxy resource with a greedy path variable of { proxy +} . Set the ANY method on the proxy resource. Integrate the resource and method with a backend using the HTTP or Lambda integration type.

Can API gateway act as a proxy?

Plus, an API gateway can act as an API proxy. An API gateway provides a much richer set of capabilities than an API proxy. When you use an API gateway to expose an API, you don't even need to start with an API.

How do I create API gateway resource?

To create the /pets resource, select the root, choose Actions and then choose Create Resource. Type Pets in Resource Name, leave the Resource Path value as given, choose Enable API Gateway CORS, and choose Create Resource. To expose a GET method on the /pets resource, choose Actions and then Create Method.


1 Answers

After a lot of playing around, I believe I found the answer in an example here. The diff relative to the Hello World example that SAM sets up for you out of the box is:

diff --git a/sam-app/template.yaml b/sam-app/template.yaml
index 02cd901..f349dcc 100644
--- a/sam-app/template.yaml
+++ b/sam-app/template.yaml
@@ -17,11 +17,11 @@ Resources:
         Variables:
           PARAM1: VALUE
       Events:
-        HelloWorld:
+        ProxyApiGreedy:
           Type: Api
           Properties:
-            Path: /hello
-            Method: get
+            Path: /{proxy+}
+            Method: ANY
 Outputs:
   HelloWorldApi:
     Description: API Gateway endpoint URL for Prod stage for Hello World function

In other words, like this:

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      ...
      Events:
        ProxyApiGreedy:
          Type: Api
          Properties:
            Path: /{proxy+}
            Method: ANY
like image 182
Alex Harvey Avatar answered Oct 24 '22 05:10

Alex Harvey