If you're building a serverless application with Lambda, chances are you need to expose your functions as APIs. That's where Amazon API Gateway comes in — and AWS SAM makes it incredibly easy to define and deploy them.

In this post, you’ll learn how to:

  • Define an API Gateway in template.yml
  • Connect it to a Lambda function
  • Understand the difference between REST API and HTTP API in terms of performance and cost

🧱 Step 1: Define the Lambda Function

Here’s a simple function that responds to HTTP requests:

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs22.x
      Events:
        HelloWorldApi:
          Type: Api
          Properties:
            Path: /hello
            Method: get

This tells SAM to automatically provision an API Gateway and connect it to your Lambda. The Path and Method define the route.

💡 Optional: Define the API Resource Explicitly

To configure advanced settings (like CORS or API type), you can explicitly define an API Gateway:

Globals:
  Api:
    Name: MyApi
    Cors:
      AllowMethods: "'GET,POST,OPTIONS'"
      AllowHeaders: "'Content-Type'"
      AllowOrigin: "'*'"

Or define the resource yourself:

Events:
  HelloWorldApi:
    Type: Api
    Properties:
      RestApiId: !Ref MyApi
      Path: /hello
      Method: get

Then connect it to your function like this:

Events:
  HelloWorldApi:
    Type: Api
    Properties:
      RestApiId: !Ref MyApi
      Path: /hello
      Method: get

🧪 Step 2: Write the Handler Code

Here’s your basic index.ts (or index.js):

export const handler = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Hello from Lambda!" }),
  };
};

⚔️ REST API vs HTTP API: Which Should You Use?

AWS offers two types of API Gateway APIs:

🚀 HTTP API (Recommended for Most Use Cases)

  • Faster cold starts
  • Lower cost (~70% cheaper than REST API)
  • Supports most common use cases (JWT auth, CORS, etc.)
  • Limited advanced features (e.g., direct VPC integration)

🧱 REST API

  • More mature, full feature set
  • Supports API keys, usage plans, request validation
  • More expensive and slightly higher latency

TL;DR:

  • Use HTTP API for most web or mobile apps
  • Use REST API if you need advanced API Gateway features

To switch to HTTP API in SAM:

Events:
  HelloWorldApi:
    Type: HttpApi
    Properties:
      Path: /hello
      Method: get

Conclusion

Creating APIs with AWS SAM is incredibly simple — just define an event and SAM handles the rest. Now you can:

✅ Connect Lambda to API Gateway
✅ Choose between REST or HTTP API based on needs