SkillSprout
Chapter 2 · Lesson 4
Intermediate
6 min read

Amazon API Gateway

Overview

Amazon API Gateway is a managed service for creating, publishing and securing APIs at any scale. It receives HTTPS requests, authenticates and throttles them, optionally transforms them and forwards them to a backend such as Lambda, an HTTP service or another AWS service.

Think of it as the reception desk of an office building. Visitors (clients) arrive at one front door; the desk checks ID (authorisation), enforces visiting limits (throttling), may translate a request into the form an employee expects (mapping) and sends them to the right department (integration).

There are three API types, and choosing the right one, plus understanding stages, authorisers, caching and CORS, is regularly tested.

Key Concepts

  • REST API: full-featured (API keys, usage plans, caching, request validation, WAF, private endpoints, mapping templates).
  • HTTP API: cheaper, lower latency, simpler; supports JWT authorisers, Lambda authorisers and IAM, with fewer features.
  • WebSocket API: two-way persistent connections with routes such as $connect, $disconnect and custom routes.
  • Lambda proxy integration passes the whole request to Lambda and expects a specific response shape; non-proxy (custom) integration uses mapping templates (VTL).
  • A stage (for example dev, prod) is a named deployment with stage variables, throttling, caching, logging and canary settings.
  • Authorisation options: IAM (SigV4), Cognito user pool authorizer, Lambda authorizer (token or request) and resource policies; HTTP APIs add JWT authorisers.
  • Default throttle is 10,000 requests/second with burst of 5,000 per account per Region; usage plans and API keys set per-client limits (REST only).
  • Integration timeout is 29 seconds by default for REST APIs (can be raised for Regional APIs with a quota increase); payload limit is 10 MB.

Detailed Notes

Choosing an API type

FeatureREST APIHTTP APIWebSocket
CostHigherAbout 70% cheaperPer message and minute
API keys / usage plansYesNoNo
CachingYesNoNo
Request validation / transformsYesLimitedRoute selection
AuthorisersIAM, Cognito, LambdaIAM, JWT, LambdaIAM, Lambda
Private (VPC-only)YesVia VPC link to private resourcesNo
WAFYesNoNo

Endpoint types

  • Edge-optimised: fronted by CloudFront, good for geographically spread clients.
  • Regional: for clients in the same Region (can add your own CloudFront).
  • Private: reachable only from a VPC through an interface endpoint.

Lambda proxy response

python
import json

def handler(event, context):
    name = (event.get("queryStringParameters") or {}).get("name", "world")
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json",
                    "Access-Control-Allow-Origin": "*"},
        "body": json.dumps({"message": f"hello {name}"}),
    }

If the response lacks statusCode and body in this shape, API Gateway returns 502 Bad Gateway. Other common codes: 504 (integration exceeded 29 s), 429 (throttled), 403 (authoriser or WAF denied), 401 (unauthorised).

Stages, deployments and variables

Changes to a REST API are not live until you create a deployment to a stage. Stage variables parameterise integrations, for example the Lambda alias:

text
arn:aws:lambda:eu-west-1:111122223333:function:Orders:${stageVariables.lambdaAlias}

Canary release settings on a stage send a percentage of traffic to a new deployment.

SAM definition

yaml
Resources:
  Api:
    Type: AWS::Serverless::HttpApi
    Properties:
      CorsConfiguration:
        AllowOrigins: ["https://app.example.com"]
        AllowMethods: [GET, POST]
  GetOrder:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs20.x
      Handler: index.handler
      Events:
        Get:
          Type: HttpApi
          Properties:
            ApiId: !Ref Api
            Path: /orders/{id}
            Method: GET

Caching and throttling

REST API stage caching (0.5 GB to 237 GB) with a TTL (default 300 s, 0-3600 s) reduces backend calls. Clients can bypass with Cache-Control: max-age=0 if permitted by IAM. Throttling applies at account, stage/method and usage plan levels.

Lambda authorizer

A Lambda authorizer receives a token or the request, and returns an IAM policy (allow/deny) with an optional context. Results can be cached by token for a TTL (default 300 s) to reduce invocations.

CORS

Browsers need Access-Control-Allow-Origin headers. For REST APIs, enable CORS (creates an OPTIONS mock integration), and for Lambda proxy the function must return the CORS headers itself.

Testing a deployed API

bash
curl -H "Authorization: Bearer $TOKEN" https://abc123.execute-api.eu-west-1.amazonaws.com/prod/orders/42

REST, HTTP and WebSocket APIs compared

FeatureREST APIHTTP APIWebSocket API
PriceHigherRoughly 70% cheaperPer message and connection minute
AuthorizersIAM, Cognito, LambdaIAM, JWT, LambdaIAM, Lambda
Usage plans and API keysYesNoNo
Request validation, caching, WAFYesLimited (no caching, WAF unsupported directly)No
Typical useFull-featured public APIsSimple low-latency proxiesChat, live dashboards

Both REST and HTTP integrations time out at about 29 seconds (REST default) to 30 seconds (HTTP), and payloads are limited to 10 MB, so long jobs need an asynchronous pattern.

CORS and errors

Browsers need CORS headers. On proxy integrations your function must return Access-Control-Allow-Origin itself, in addition to the preflight (OPTIONS) response configured on the API.

CodeTypical cause
400Failed request validation
401 / 403Authorizer denied, missing or invalid token, WAF block
429Throttling (account, stage or usage-plan limit)
502Malformed Lambda proxy response or function error
504Integration exceeded the timeout

Stage-level throttling defaults to 10,000 requests per second with a burst of 5,000 per account and Region; usage plans add per-key limits. Turn on access logging (a JSON format with $context.requestId, $context.error.message) and X-Ray for each stage to debug.

Real World Example

A SaaS vendor exposes a public REST API to paying customers. They give each customer an API key tied to a usage plan (Basic: 10 req/s, 10,000 per day; Pro: 100 req/s), protect it with WAF rate rules, authorise end users through a Cognito authorizer, and enable stage caching for the read-heavy catalogue endpoint. Latency for cached calls dropped from 180 ms to 12 ms and Lambda invocations fell by 60%.

Architecture Diagram

API Gateway in front of Lambda
Architecture
AWS Cloud
Client

API Gateway

Authorizer
Stage: prodthrottle + cache
Lambda
DynamoDB

Authorise, throttle and cache at the edge of your application.

  1. 1The client calls the stage URL over HTTPS.
  2. 2The authoriser validates the token or signature.
  3. 3Throttling, validation and caching rules are applied.
  4. 4The request reaches Lambda, which reads or writes the database and returns a response.

Best Practices

  • ✓Choose HTTP API unless you need REST-only features.
  • ✓Use Cognito/JWT or IAM authorisation; reserve API keys for metering, not security.
  • ✓Enable access logging and X-Ray tracing on stages.
  • ✓Return proper CORS headers from proxy-integrated functions.
  • ✓Use stage variables and aliases for environment promotion.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Per-client rate limits and quotas -> usage plans with API keys (REST).
  • 29 seconds is the standard integration timeout (504 on exceed).
  • Reduce backend load for repeated GETs -> API Gateway stage caching.
  • Gradual API change rollout -> stage canary settings.

Chapter quiz

Serverless with Lambda and API Gateway · 10 questions

  1. 1.A Lambda function creates a new DynamoDB client at the start of every invocation, adding latency. What is the best fix?

  2. 2.An SQS-triggered function processes batches of 10. Occasionally one bad message causes all 10 to be reprocessed. What should the developer enable?

  3. 3.A team wants to roll out a new Lambda version to 10% of users first and automatically roll back if errors increase. Which approach fits?

  4. 4.A REST API with Lambda proxy integration returns 502 Bad Gateway. The function runs successfully and returns the string "ok". What is the likely cause?

  5. 5.A critical Lambda function is throttled because another function in the account consumes most of the concurrency. Which change protects it?

  6. 6.A Lambda function in a VPC private subnet must call the public Stripe API and also read DynamoDB. Which setup works with the least exposure?

  7. 7.An asynchronous Lambda invocation fails after its retries and the event must be kept for analysis along with error details. What is the best option?

  8. 8.A SQS-triggered function processes batches of 10 messages. One bad message causes the whole batch to be retried. How do you avoid reprocessing the good ones?

  9. 9.A team wants to shift 10 percent of API traffic to a new Lambda version, then the rest after verification, with automatic rollback on alarms. Which approach fits?

  10. 10.A REST API method needs to reject requests missing a required JSON field before Lambda runs. What should you configure?

0 of 10 answered

Finished this lesson?

0 of 46 lessons done · 0% of the course