0

I am currently learning AWS Serverless Application Model (SAM).

With that objective, I created a simple template that is deploying a Python Lambda function and an API which calls this function. My template is the following :

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  a test with AWS SAM

Globals:
  Function:
    Timeout: 10
  Api:
    OpenApiVersion: 3.0.1

Resources:
  HelloAPI:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      Auth:
        ApiKeyRequired: true
        UsagePlan:
          CreateUsagePlan: PER_API
          Description: Usage plan for this API
  HelloFunction:
    Properties:
      CodeUri: some/path/to/hello_function
      Handler: hello.lambda_handler
      Runtime: python3.8
      Events:
        Hello:
          Type: Api 
          Properties:
            RestApiId: !Ref HelloAPI
            Path: /
            Method: post        

Outputs:
  ProdDataEndpoint:
    Description: "API dev stage endpoint"
    Value: !Sub "https://${HelloAPI}.execute-api.${AWS::Region}.amazonaws.com/dev/"

So the template creates a UsagePlan with an associated API key. I checked within AWS, the ressources are indeed created correcly.

I can test the API locally with :

sam local start-api
sam local generate-event apigateway aws-proxy > local-event.json
curl -d "@local-event.json" -X POST http://127.0.0.1:3000/

And this works. But I don't know how to test it with the API key to check if the access is indeed protected by the key. Does anyone know how to do that?

Thanks !

FenryrMKIII
  • 1,068
  • 1
  • 13
  • 30
  • Generally when trying to test infrastructure the only safe way to test it is to actually deploy it into a dedicated AWS account, run the test against that and then cleanup everything afterwards. – luk2302 May 31 '21 at 07:11
  • Thanks. Ok I was thinking maybe this was included in the sam cli or aws toolkit in VSCode. Is there a way with curl to include the API key in the call ? (I am completely new to API) – FenryrMKIII May 31 '21 at 09:44
  • *Maybe* it is, not sure about SAM specifically. But as you think about the lambda accessing e.g. a dynamodb or SQS or whatever you will run into the same problem again, there are mock apis for a few services available, but especially the IAM-side of things is ignored / skipped most of the time. – luk2302 May 31 '21 at 09:46
  • I believe you can't do this locally, you can test the lambda invocation, but not the API gateway itself. – me2resh Jun 16 '21 at 18:05

0 Answers0