How to Create Mock API Endpoints with AWS API Gateway, CloudFormation and OpenAPI

July 21, 2025 • 3 min read

AWS API Gateway offers a powerful mocking feature that, when combined with CloudFormation, allows you to quickly spin up mock APIs without writing any backend code. In this article, we’ll explore how to create a fully functional mock endpoint using AWS API Gateway’s integration with OpenAPI specifications and Infrastructure as Code principles through CloudFormation. This approach is perfect for rapid prototyping, parallel frontend/backend development, and creating demo environments.

CloudFormation Template

---
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Description: Mocked API
Parameters:
  AppName:
    Description: Name of application
    Type: String
  Environment:
    Type: String
    Description: Environment name - dev, int, prd, etc

Resources:
  RestApi:
    Type: AWS::Serverless::Api
    Properties:
      Name: !Sub ${AppName}-${Environment}
      StageName: !Ref Environment  # Explicitly set stage name
      OpenApiVersion: 3.0.2
      EndpointConfiguration:
        Type: REGIONAL
      TracingEnabled: true
      Cors:  # Optional: Enable CORS for browser testing
        AllowMethods: "'GET,POST,OPTIONS'"
        AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
        AllowOrigin: "'*'"
      DefinitionBody:
        !Transform
          Name: AWS::Include
          Parameters:
            Location: openapi.yaml
Outputs:
  ApiUrl:
    Description: API Gateway endpoint URL
    Value: !Sub 'https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/${Environment}'

OpenAPI Spec

---
openapi: 3.0.2
info:
  version: '1.0.0'
  title: aws-apigw-mocked-endpoint

paths:
  /mocked:
    get:
      summary: Returns mocked data
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                  timestamp:
                    type: string
                  data:
                    type: array
                    items:
                      type: object
      x-amazon-apigateway-integration:
        type: mock
        requestTemplates:
          application/json: |
            {
              "statusCode": 200
            }
        responses:
          default:
            statusCode: "200"
            responseTemplates:
              application/json: |
                {
                  "message": "This is a mocked response",
                  "timestamp": "$context.requestTime",
                  "data": [
                    {"id": 1, "name": "Sample Item 1"},
                    {"id": 2, "name": "Sample Item 2"}
                  ]
                }
        passthroughBehavior: when_no_match

Additional Mock Response Examples

Star Wars Characters List

/star-wars/characters:
  get:
    x-amazon-apigateway-integration:
      type: mock
      responses:
        default:
          statusCode: "200"
          responseTemplates:
            application/json: |
              {
                "characters": [
                  {"id": 1, "name": "Luke Skywalker", "species": "Human", "homeworld": "Tatooine"},
                  {"id": 2, "name": "Darth Vader", "species": "Human", "homeworld": "Tatooine"},
                  {"id": 3, "name": "Yoda", "species": "Yoda's species", "homeworld": "Unknown"},
                  {"id": 4, "name": "Princess Leia", "species": "Human", "homeworld": "Alderaan"},
                  {"id": 5, "name": "Han Solo", "species": "Human", "homeworld": "Corellia"},
                  {"id": 6, "name": "Chewbacca", "species": "Wookiee", "homeworld": "Kashyyyk"},
                  {"id": 7, "name": "R2-D2", "species": "Droid", "homeworld": "Naboo"},
                  {"id": 8, "name": "C-3PO", "species": "Droid", "homeworld": "Tatooine"}
                ],
                "count": 8,
                "timestamp": "$context.requestTime"
              }

User Profile

/user/profile:
  get:
    x-amazon-apigateway-integration:
      type: mock
      responses:
        default:
          statusCode: "200"
          responseTemplates:
            application/json: |
              {
                "user": {
                  "id": "usr_$context.requestId",
                  "username": "johndoe",
                  "email": "john.doe@example.com",
                  "firstName": "John",
                  "lastName": "Doe",
                  "avatar": "https://ui-avatars.com/api/?name=John+Doe",
                  "joinDate": "2023-01-15T10:30:00Z",
                  "preferences": {
                    "theme": "dark",
                    "language": "en",
                    "notifications": true
                  }
                },
                "requestTime": "$context.requestTime",
                "apiVersion": "1.0.0"
              }

Error Response Mock

/error-example:
  get:
    x-amazon-apigateway-integration:
      type: mock
      responses:
        default:
          statusCode: "400"
          responseTemplates:
            application/json: |
              {
                "error": {
                  "code": "INVALID_REQUEST",
                  "message": "The request could not be processed",
                  "details": "Missing required parameter: userId",
                  "timestamp": "$context.requestTime",
                  "requestId": "$context.requestId"
                }
              }

Deploying Your Mock API with AWS SAM CLI

To deploy this mock API to AWS, you’ll need the AWS SAM CLI installed. First, ensure your files are organized with template.yaml (the CloudFormation file) and openapi.yaml in the same directory. Then, run the following commands:

# Build the SAM application
sam build

# Deploy with guided prompts (first time)
sam deploy --guided

# Or deploy with parameters directly
sam deploy --parameter-overrides AppName=my-mock-api Environment=dev

During the guided deployment, SAM will prompt you for the stack name, AWS region, and parameter values. It will also create a samconfig.toml file to save your choices for future deployments. Once deployed, you can find your API endpoint URL in the CloudFormation outputs or by running:

# Get the API endpoint URL -- which will be the CloudFormation output property "ApiUrl"
aws cloudformation describe-stacks --stack-name <your-stack-name> --query 'Stacks[0].Outputs'

You can then test your mock endpoint by making a GET request to https://<api-id>.execute-api.<region>.amazonaws.com/<stage>/mocked. To update your mock responses, simply modify the openapi.yaml file and run sam deploy again. When you’re done experimenting, clean up your resources with sam delete to avoid any unnecessary AWS charges.