Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Amazon API Gateway

Concise study notes on Amazon API Gateway: what it is, core concepts (resources, methods, integrations, stages), security and deployment patterns, CLI/console syntax to remember, worked request-flow and CORS examples, common exam mistakes and practice questions.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Amazon API Gateway is the managed AWS service that exposes APIs (HTTP/REST/WebSocket) to clients and routes requests to backends (Lambda, HTTP endpoints, AWS services). Engineers use it to design, secure, deploy and scale serverless or hybrid APIs that act as the front door of cloud applications.

Key ideas

Start with definitions (I define each term before using it):

  • API: Application Programming Interface — a defined set of HTTP endpoints (URLs), methods and message formats that let clients talk to a service.
  • Amazon API Gateway (API GW): a managed AWS service that receives API requests, applies configuration (authorization, throttling, mapping, caching), and forwards to an integration (Lambda, HTTP endpoint, AWS service) then returns a response to the client.
  • REST API (API GW v1): API Gateway model supporting REST-style APIs with resources and methods, rich mapping templates (VTL), and many legacy features.
  • HTTP API (API GW v2): newer, cheaper, lower-latency API type for most RESTful use-cases; supports JWT authorizers, Lambda integrations, simpler mapping.
  • WebSocket API: API type that maintains persistent WebSocket connections; used for real-time two-way communication. WebSocket routes include special routes $connect, $disconnect, and $default.
  • Resource: a path segment under an API (for example "/items"). A resource can have child resources (e.g., "/items/{id}").
  • Method: an HTTP verb (GET, POST, PUT, DELETE, OPTIONS, etc.) attached to a Resource.
  • Stage: a named deployment environment (for example "dev", "prod") that points to a specific Deployment. A Stage has configuration like variables, logging, cache, and can host stage-level settings and canary deployment settings. Note: Stage variables, caching, and canary deployments are features of REST APIs; HTTP APIs do not support stage variables or caching and do not support canary, but they do support access logging and an auto-deploy option that deploys changes to a stage automatically.
  • Deployment: an immutable snapshot of API configuration (resources, methods, integrations, mapping templates) that can be associated to a Stage.
  • Integration: the backend target for a method. Common integrations: Lambda function, HTTP endpoint, AWS service (e.g., Kinesis), Mock (used for testing). Integrations can be proxy or non-proxy.
  • Lambda proxy integration: API GW forwards the entire HTTP request (method, path, headers, body) to a Lambda as a JSON event and expects the Lambda to return a JSON with statusCode, headers, and body (string). This requires minimal mapping templates.
  • Non-proxy (custom) integration: you define mapping templates for the request and response so API GW translates between HTTP and backend formats.
  • Mapping template: a template (Velocity Template Language, VTL) that transforms the incoming request into the format the integration expects, or transforms the integration response into the HTTP response.
  • Method request / Integration request / Method response / Integration response: the four logical stages where you can validate and transform data. Method request is the incoming HTTP request; Integration request is what goes to backend; Integration response is what comes from backend; Method response is sent to client.
  • CORS: Cross-Origin Resource Sharing — HTTP headers that allow browsers to call your API from a different origin. CORS is implemented by adding the correct response headers (Access-Control-Allow-Origin, etc.) typically on an OPTIONS method or in responses. For HTTP APIs, you can enable CORS at the API level via settings that automatically add the appropriate headers; for REST APIs you typically configure CORS per resource/method (or use the console helper).
  • Authorizer: a piece of configuration that decides who can call the API. AWS supports IAM (SigV4), Cognito User Pools, and Lambda authorizers (custom). HTTP APIs support JWT authorizers and also support IAM authorization and Lambda authorizers.
  • Resource policy: a JSON policy attached to the API that controls which AWS principals, VPC endpoints, or source IPs can invoke the API (useful for private APIs or restricting by VPC endpoint).
  • Usage plan & API key: Usage plan sets request rate/burst and quota; associate API keys to restrict and meter clients. (REST APIs only; HTTP APIs do not support usage plans or API keys.)
  • Throttling: API GW enforces limits by two parameters: rate (requests per second) and burst (allowance for sudden spikes). Requests beyond limits are rejected with HTTP 429.
  • Caching: API GW stage-level cache stores method responses for a TTL to reduce backend load. Cache keys include path, query, and headers you configure. (REST APIs only.)
  • Endpoint types: REST APIs support Edge-optimized (uses CloudFront), Regional, and Private (accessible only inside VPC via interface VPC endpoints / AWS PrivateLink). HTTP APIs support Regional and Private (no Edge-optimized). WebSocket APIs are Regional only. You can also configure custom domain names with ACM certificates and base path mappings to stages.

Request lifecycle (exact steps you should be able to write in an exam):

  1. Client sends HTTP request to API endpoint (edge or regional URL).
  2. API GW receives request and enforces resource policy (if any).
  3. API GW evaluates a matching Resource and Method.
  4. API GW checks authorization (IAM/Cognito/Lambda). If rejection, respond 401/403.
  5. API GW enforces throttling and, for REST APIs, any usage plan limits.
  6. If method has request validation, API GW validates parameters/body.
  7. API GW applies integration request mapping template to produce backend payload.
  8. API GW sends request to integration (Lambda, HTTP backend, AWS service).
  9. Backend responds; API GW applies integration response mapping templates to build HTTP response.
  10. API GW returns final HTTP response to client with headers, status code, and body.

Diagram to draw for an exam (describe exactly what to draw and label):

  • Draw a left box labeled "Client (Browser / Mobile)" with an arrow to a central box labeled "API Gateway". Inside API Gateway box, draw stacked elements and label: "Resource/Method -> Auth -> Throttling -> Mapping Templates -> Integration". Draw an arrow from API Gateway to a right box labeled "Backend (Lambda / HTTP / AWS Service)". Draw arrow back to API Gateway, then back to Client. Label request and response at arrows. Also draw a separate box under API Gateway labeled "Stage (dev/prod), Caching, Logging" connected to the API Gateway box.

Assumptions behind the model: API GW is stateless per request; Lambda integrations are invoked asynchronously or synchronously depending on configuration (default is synchronous for request-response). HTTP APIs reduce mapping template complexity. Maximum integration timeout is 29 seconds; maximum payload size for request and response is 10 MB for synchronous invocations.

Formulas

aws apigateway create-rest-api --name MyApi --region ap-south-1 — create a REST API (API GW v1).

aws apigatewayv2 create-api --name MyHttpApi --protocol-type HTTP --region ap-south-1 — create an HTTP API (API GW v2).

aws apigateway create-resource --rest-api-id <id> --parent-id <root-id> --path-part items — create /items resource (REST API).

aws apigateway put-method --rest-api-id <id> --resource-id <rid> --http-method POST --authorization-type NONE — attach POST method.

Example Lambda proxy response format (syntax to remember — statusCode must be an integer, body must be a string, isBase64Encoded is optional):

{ "statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": "...stringified JSON...", "isBase64Encoded": false }

Minimal VTL mapping to pass JSON body to an integration:

#set($inputRoot = $input.path('$'))
$input.json('$')

Resource policy JSON skeleton to restrict source IPs (syntax to memorize):

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": "*",
      "Action": "execute-api:Invoke",
      "Resource": "arn:aws:execute-api:REGION:ACCOUNT_ID:API_ID/STAGE/VERB/RESOURCE",
      "Condition": { "IpAddress": { "aws:SourceIp": ["203.0.113.0/24"] } }
    }
  ]
}

Note: replace REGION, ACCOUNT_ID, API_ID appropriately.

Worked examples

Example 1 — Trace a POST request through an HTTP API with Lambda proxy integration (step-by-step): Given: HTTP API has route POST /items integrated with Lambda function MyCreateItem (proxy). Client sends:

Steps:

  1. Client sends POST. API GW receives request and matches route POST /items.
  2. Authorizer: assume NONE. Throttling: within limits.
  3. For Lambda proxy, API GW builds an event JSON like: { "version": "2.0", "routeKey": "POST /items", "rawPath": "/items", "headers": {"content-type":"application/json"}, "body": "{ \"name\": \"pen\", \"qty\": 10 }" } and invokes Lambda synchronously.
  4. Lambda MyCreateItem parses the event.body JSON, performs logic, and returns: { "statusCode": 201, "headers": {"Content-Type":"application/json"}, "body": "{ \"id\": \"abc\", \"name\": \"pen\" }" }.
  5. API GW forwards that to the client as HTTP/1.1 201 Created, with header Content-Type: application/json and the body string.

Final answer (what the client sees): HTTP 201, body {"id":"abc","name":"pen"}. Markers to check: Lambda must return statusCode (integer) and body (string) for proxy; include isBase64Encoded when returning binary data.

Example 2 — Enable CORS for GET /items using OPTIONS method and mapping headers (step-by-step): Goal: Browser must be allowed to call GET /items from https://example.com.

Steps:

  1. On resource /items create an OPTIONS method that returns 200 and includes headers:
    • Access-Control-Allow-Origin: https://example.com
    • Access-Control-Allow-Methods: GET,POST,OPTIONS
    • Access-Control-Allow-Headers: Content-Type,Authorization
  2. In the OPTIONS method create a Mock integration (no backend). Set Integration Response to include mapping that returns the above headers.
  3. For GET method, ensure Method Response contains response header mappings so API GW passes Access-Control-Allow-Origin in actual responses.

Minimal mapping (integration response) for OPTIONS (VTL or static response):

statusCode: 200
headers:
  Access-Control-Allow-Origin: https://example.com
  Access-Control-Allow-Methods: GET,POST,OPTIONS
  Access-Control-Allow-Headers: Content-Type,Authorization

Result: Browser preflight (OPTIONS) receives 200 and allowed headers; subsequent GET is permitted.

Checkpoints: remember to add CORS headers to actual responses or configure gateway to add them.

Common mistakes

  • Forgetting to add CORS headers to actual method responses, only adding them to OPTIONS, so browser still blocks.
  • Returning a raw object from Lambda without the statusCode/body shape when using Lambda proxy integration.
  • Misplacing authorizers: thinking API Gateway automatically authenticates with Cognito if a user pool exists (you must explicitly attach a Cognito authorizer).
  • Mixing up endpoint types: trying to use edge-optimized endpoints in a VPC-only private API scenario.
  • Ignoring stage variables and deployments: editing resources in console without creating a new deployment and stage mapping.

For your exam

Possible question types:

  • Definitions and short notes: define Resource, Method, Stage, Integration, Mapping Template.
  • Diagrams: draw request flow and label components (client, API GW, integration, stage, caching).
  • Derivation / explanation: explain how API GW enforces throttling and how usage plans relate to API keys.
  • Configuration/commands: show CLI commands to create an API, resource and method, or show a minimal VTL mapping template.
  • Small program/trace: given a Lambda function and an incoming HTTP request, show the event JSON and the final response.

What full-marks answers include:

  • Precise definitions with bold terms, correct order of request processing steps (auth, throttling, mapping, integration, response mapping).
  • A correctly labeled diagram when asked.
  • Correct example commands or code snippets with required fields (e.g., Lambda proxy response contains statusCode, headers, body).
  • Notes on edge cases: CORS, private APIs, and whether mapping templates are needed.

Quick check

  1. What header must you set if you want browser JavaScript from https://site.example to call your API? (name only)
  2. What key fields must a Lambda return when used with Lambda proxy integration so API GW can form an HTTP response?
  3. Name two integration types supported by API Gateway.

Answers: 1) Access-Control-Allow-Origin 2) statusCode, headers, body 3) Lambda integration, HTTP integration (also AWS service and Mock)

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?