Home > Software engineering >  Simple API gateway with Mock response defined in SAM?
Simple API gateway with Mock response defined in SAM?

Time:10-24

I have a simple API gateway definition in AWS.

It has a single Method for "/" with a "GET" HTTP type.

I've updated the "Integration Request" to be a "Mock" (return a response purely with API Gateway mappings ...).

There's nothing fancy, all requests will be passed through.

For the response, I've updated the default Integration Response ( response status 200, no regex, model etc. Default mapping).

It has an "application/json" Mapping template, and in here i have just added the static text "hello world" (creative, i know).

Now, the question is, can i define this in a SAM template ?

I can readily find plenty of exmaples to create a lambda function behind this and have it do the response and all sorts of other things.

I can run the SAM cli locally to do "sam deploy" giving the sam template, and have a whole new AWS Stack created in my account, with the API Gateway created, the lambda python or javascript or etc uploaded to s3 and created and linked in to the API (through implicit sam definition, no external oas/swagger looked at yet) and roles etc created.

And it all works beautifully.

But if I want to do the same thing, but simpler - with just API gateway only and a mock integration response (no lambda) - what would the SAM template look like for that ?

As of yet, i am at a loss.

I can see from the serverless model that a lot of the integrations are supported in sam (x-amazon-apigateway-integration response).

I can see what the oas version looks like by using "api-gateway getexport" via the aws cli.

But I can not see a SAM template with implicit API creation that has no lambda linked in, just a simple Mock and static integration response.

Any help appreciated !!

CodePudding user response:

SAM is a extension of Cloudformation, so yeah, it is possible, if you create a sam application and add the bellow template.yaml file, and run sam deploy --guided you will create what you need. In this case you will be running a simple cloudformation template that can be deployed with the following command:

aws cloudformation deploy --stack-name mock-api --template-file template.yaml

The main idea of SAM is facilitate the deploy of Serverless aplications, creating a possibility of invoke Lambda functions locally, improve debugging and so on, while provisioning your resources.

As we can see in the AWS documentation:

A serverless application is a combination of Lambda functions, event sources, and other resources that work together to perform tasks. Note that a serverless application is more than just a Lambda function—it can include additional resources such as APIs, databases, and event source mappings

So, if you are not using Lambda and you want provision your resources, you can simply use Cloudformation or another IaC tool as Terraform.

template.yml example (of what you need):

AWSTemplateFormatVersion: '2010-09-09'

Description: AWS API Gateway with a Mock Integration

Resources:

  ApiGatewayRestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      ApiKeySourceType: HEADER
      Description: An API Gateway with a Mock Integration
      EndpointConfiguration:
        Types:
          - EDGE
      Name: mock-api

  ApiGatewayResource:
    Type: AWS::ApiGateway::Resource
    Properties:
      ParentId: !GetAtt ApiGatewayRestApi.RootResourceId
      PathPart: 'mock'
      RestApiId: !Ref ApiGatewayRestApi

  ApiGatewayMethod:
    Type: AWS::ApiGateway::Method
    Properties:
      ApiKeyRequired: false
      AuthorizationType: NONE
      HttpMethod: POST
      Integration:
        ConnectionType: INTERNET
        IntegrationResponses:
          - ResponseTemplates:
              application/json: "{\"message\": \"OK\"}"
            SelectionPattern: '2\d{2}'
            StatusCode: 200
          - ResponseTemplates:
              application/json: "{\"message\": \"Internal Server Error\"}"
            SelectionPattern: '5\d{2}'
            StatusCode: 500
        PassthroughBehavior: WHEN_NO_TEMPLATES
        RequestTemplates:
          application/json: "{\"statusCode\": $input.json('$.statusCode'), \"message\": $input.json('$.message')}"
        Type: MOCK
        TimeoutInMillis: 29000
      MethodResponses:
        - ResponseModels:
            application/json: !Ref ApiGatewayModel
          StatusCode: 200
        - ResponseModels:
            application/json: !Ref ApiGatewayModel
          StatusCode: 500
      OperationName: 'mock'
      ResourceId: !Ref ApiGatewayResource
      RestApiId: !Ref ApiGatewayRestApi

  ApiGatewayModel:
    Type: AWS::ApiGateway::Model
    Properties:
      ContentType: 'application/json'
      RestApiId: !Ref ApiGatewayRestApi
      Schema: {}

  ApiGatewayStage:
    Type: AWS::ApiGateway::Stage
    Properties:
      DeploymentId: !Ref ApiGatewayDeployment
      Description: Mock API Stage v0
      RestApiId: !Ref ApiGatewayRestApi
      StageName: 'v0'

  ApiGatewayDeployment:
    Type: AWS::ApiGateway::Deployment
    DependsOn: ApiGatewayMethod
    Properties:
      Description: Mock API Deployment
      RestApiId: !Ref ApiGatewayRestApi

CodePudding user response:

To do this - with SAM - i have

  • manually created a simple API gateway with a single GET and a mock response of static text in the integration response.
  • exported that with aws apigateway get-export
  • remove the servers and policy blocks (those i'll have in my sam template)
  • refer to the OAS spec in your SAM template in the API properties with DefinitionBody
  • upload the OAS spec
  • use SAM deploy

It looks like this is required if you want to include mocks in deployable with sam, as the SAM specifications doesn't include enough options to specify mock integration responses.

There may be other ways with SAM i haven't come across yet.

Thanks to @valdeci, and Jens Eickmeyer for this post

  • Related