Fatskills
Practice. Master. Repeat.
Study Guide: TECH **Amazon API Gateway (REST, HTTP, WebSocket) – Zero-Fluff Study Guide**
Source: https://www.fatskills.com/aws-certified-solutions-architect-associate/chapter/tech-amazon-api-gateway-rest-http-websocket-zero-fluff-study-guide

TECH **Amazon API Gateway (REST, HTTP, WebSocket) – Zero-Fluff Study Guide**

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~9 min read

Amazon API Gateway (REST, HTTP, WebSocket) – Zero-Fluff Study Guide

For AWS Solutions Architect – Associate (SAA-C03) & Real-World Deployments


1. What This Is & Why It Matters

You’re a cloud engineer at a fintech startup. Your team built a microservice in Lambda that processes payments, but now the frontend team needs a way to call it securely. The backend team insists on rate limiting to prevent abuse, and the security team demands audit logs for every request. API Gateway is the Swiss Army knife that solves all of this in one place.

What breaks if you ignore it?
- No security: Your Lambda functions are exposed directly to the internet (bad).
- No scalability: You’ll manually handle spikes in traffic (impossible at scale).
- No observability: You won’t know who’s calling your API or how often.
- No cost control: Unlimited requests = unlimited bills.

What superpower does it give you?
- Single entry point for all your backend services (Lambda, EC2, ECS, HTTP endpoints).
- Built-in security (IAM, Cognito, API keys, WAF integration).
- Traffic control (throttling, caching, request/response transformations).
- Real-time updates (WebSocket APIs for chat apps, live dashboards, or stock tickers).

Real-world scenario:
You inherit a legacy monolith that exposes a REST API directly from an EC2 instance. Your task: 1. Migrate to serverless (Lambda + API Gateway).
2. Add authentication (Cognito).
3. Cache responses to reduce Lambda invocations (cost savings).
4. Log every request to CloudWatch for compliance.


2. Core Concepts & Components


1. REST API

  • What it is: Traditional request-response API (like a vending machine: you insert a coin, get a soda).
  • Production insight: Use for CRUD operations (e.g., GET /users, POST /orders). ⚠️ REST APIs are regional—deploy in multiple regions for global apps.

2. HTTP API

  • What it is: A lighter, faster, cheaper version of REST API (no request validation, but 70% cheaper).
  • Production insight: Use for internal microservices or when you don’t need advanced features like caching or request transformations. ⚠️ No support for AWS_IAM auth (use Lambda authorizers instead).

3. WebSocket API

  • What it is: Persistent, bidirectional connection (like a phone call vs. REST’s walkie-talkie).
  • Production insight: Use for real-time apps (chat, live sports scores, trading platforms). ⚠️ WebSocket APIs are stateful—you must manage connection IDs.

4. Resources & Methods

  • What it is: A "resource" is a URL path (e.g., /users), and a "method" is an HTTP verb (GET, POST, etc.).
  • Production insight: Never expose DELETE methods publicly—use IAM or API keys to restrict them.

5. Integration Types

  • Lambda: Trigger a Lambda function.
  • HTTP: Proxy to an existing HTTP endpoint (e.g., EC2, ALB, or external API).
  • Mock: Return a static response (useful for testing).
  • AWS Service: Directly invoke AWS services (e.g., DynamoDB, S3).
  • VPC Link: Connect to private resources in a VPC (e.g., ECS, RDS).
  • Production insight: Lambda integrations are the most common—but HTTP integrations are cheaper for high-throughput APIs.

6. Stages

  • What it is: A snapshot of your API at a point in time (e.g., dev, prod, v1).
  • Production insight: Always use stages for environment separation—never deploy directly to prod. Use stage variables to change backend endpoints per stage.

7. Deployments

  • What it is: A version of your API tied to a stage (e.g., v1.2prod).
  • Production insight: Deployments are immutable—if you break something, roll back to a previous deployment.

8. Authorizers

  • Lambda Authorizer: Custom logic (e.g., validate a JWT from Auth0).
  • Cognito Authorizer: Use AWS Cognito for user pools.
  • IAM Authorizer: Use AWS IAM roles/policies (for internal services).
  • Production insight: Lambda authorizers add latency (~100ms per request). Cache results to reduce costs.

9. Usage Plans & API Keys

  • What it is: Rate limiting and throttling (e.g., 1000 requests/month per API key).
  • Production insight: Always set usage plans for public APIs—otherwise, you’ll get DDoS’d or hit Lambda concurrency limits.

10. Caching

  • What it is: Store responses in memory (TTL: 0s–3600s).
  • Production insight: Cache GET requests aggressively (e.g., product listings). Never cache POST/PUT/DELETE (they modify data).

11. Custom Domain Names

  • What it is: Map api.yourcompany.com to your API Gateway.
  • Production insight: Use ACM (AWS Certificate Manager) for HTTPS—never use HTTP in production.

12. Logging & Monitoring

  • CloudWatch Logs: Full request/response logs (enable for debugging).
  • CloudWatch Metrics: Track 4XXError, 5XXError, Latency, Count.
  • X-Ray: Trace requests end-to-end (e.g., API Gateway → Lambda → DynamoDB).
  • Production insight: Enable CloudWatch Logs for all APIs—you’ll regret it if you don’t when debugging.


3. Step-by-Step Hands-On: Deploy a REST API with Lambda Integration

Prerequisites:
- AWS account with admin IAM permissions.
- AWS CLI installed (aws --version).
- A Lambda function (we’ll create one).

Step 1: Create a Lambda Function

# Create a Lambda function (Python 3.9)
aws lambda create-function \
  --function-name HelloWorld \
  --runtime python3.9 \
  --role arn:aws:iam::YOUR_ACCOUNT_ID:role/lambda-basic-execution \
  --handler lambda_function.lambda_handler \
  --zip-file fileb://function.zip

function.zip contents (lambda_function.py):


def lambda_handler(event, context):
return {
"statusCode": 200,
"body": "Hello from Lambda!"
}

Verify:


aws lambda invoke --function-name HelloWorld output.txt && cat output.txt
# Expected: {"statusCode": 200, "body": "Hello from Lambda!"}

Step 2: Create a REST API

# Create the API
aws apigateway create-rest-api --name 'HelloWorld API' --description 'My first API'

Note the id in the response (e.g., abc123).

Step 3: Get the Root Resource ID

aws apigateway get-resources --rest-api-id abc123

Note the id of the root resource (e.g., def456).

Step 4: Create a Resource (/hello)

aws apigateway create-resource \
  --rest-api-id abc123 \
  --parent-id def456 \
  --path-part hello

Note the new resource ID (e.g., ghi789).

Step 5: Create a GET Method

aws apigateway put-method \
  --rest-api-id abc123 \
  --resource-id ghi789 \
  --http-method GET \
  --authorization-type NONE

Step 6: Integrate with Lambda

aws apigateway put-integration \
  --rest-api-id abc123 \
  --resource-id ghi789 \
  --http-method GET \
  --type AWS_PROXY \
  --integration-http-method POST \
  --uri arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:YOUR_ACCOUNT_ID:function:HelloWorld/invocations

⚠️ Replace YOUR_ACCOUNT_ID with your actual AWS account ID.

Step 7: Deploy the API

aws apigateway create-deployment \
  --rest-api-id abc123 \
  --stage-name prod

Note the invokeUrl in the response (e.g., https://abc123.execute-api.us-east-1.amazonaws.com/prod).

Step 8: Test the API

curl https://abc123.execute-api.us-east-1.amazonaws.com/prod/hello
# Expected: "Hello from Lambda!"

Step 9: Enable CloudWatch Logs (Optional but Recommended)

aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:us-east-1:YOUR_ACCOUNT_ID:log-group:API-Gateway-Execution-Logs_abc123/prod


4. ? Production-Ready Best Practices


Security

  • IAM: Use IAM authorizers for internal services (e.g., microservices calling each other).
  • Cognito: Use Cognito authorizers for user-facing APIs (e.g., mobile apps).
  • API Keys: Use for third-party developers (but never for authentication—they’re just for rate limiting).
  • WAF: Attach AWS WAF to block SQLi, XSS, and DDoS attacks.
  • VPC Endpoints: Use PrivateLink (com.amazonaws.vpce.us-east-1.vpce-svc-xyz) to keep API Gateway traffic inside your VPC.

Cost Optimization

  • HTTP API > REST API: HTTP APIs are 70% cheaper and faster (but lack features like caching).
  • Caching: Enable caching for GET requests (TTL: 1–300s).
  • Usage Plans: Set rate limits to prevent abuse (e.g., 1000 requests/month per API key).
  • Lambda Proxy: Use AWS_PROXY integration to avoid manual request/response mapping.

Reliability & Maintainability

  • Stages: Always use dev, staging, prod (never deploy directly to prod).
  • Stage Variables: Use them to change backend endpoints per stage (e.g., LambdaArn: ${stageVariables.LambdaArn}).
  • Canary Deployments: Roll out changes to 10% of traffic first.
  • Tags: Tag APIs with Environment=prod, Owner=team-x, CostCenter=123.

Observability

  • CloudWatch Alarms: Set alarms for 5XXError > 0 or Latency > 1000ms.
  • X-Ray: Enable tracing to debug latency issues (e.g., API Gateway → Lambda → DynamoDB).
  • Custom Metrics: Log business metrics (e.g., SuccessfulPayments, FailedLogins).


5. ⚠️ Common Mistakes & Traps

Mistake Symptom Fix/Prevention
No usage plan API gets DDoS’d, Lambda concurrency limit hit. Always set rate limits (e.g., 1000 requests/month per API key).
No caching High Lambda costs, slow responses. Cache GET requests (TTL: 1–300s).
No CloudWatch Logs Can’t debug failed requests. Enable logs for all APIs.
Hardcoded ARNs API breaks when Lambda is updated. Use stage variables (e.g., ${stageVariables.LambdaArn}).
No CORS Frontend gets No 'Access-Control-Allow-Origin' header errors. Enable CORS in API Gateway (or handle it in Lambda).
No WAF API gets hacked (SQLi, XSS). Attach AWS WAF to block common attacks.


6. ? Exam/Certification Focus


Typical Question Patterns

  1. "Which API Gateway type is cheapest?"
  2. Answer: HTTP API (but lacks features like caching).
  3. Trap: REST API is more expensive but has more features.

  4. "How do you secure an API for mobile users?"

  5. Answer: Cognito authorizer (not IAM or API keys).
  6. Trap: API keys are for rate limiting, not authentication.

  7. "How do you reduce latency for a global API?"

  8. Answer: Use API Gateway + Lambda@Edge (not just API Gateway alone).
  9. Trap: API Gateway is regional—use CloudFront for global caching.

  10. "How do you debug a 500 error in API Gateway?"

  11. Answer: Check CloudWatch Logs (not just Lambda logs).
  12. Trap: Lambda logs won’t show API Gateway errors.

  13. "How do you roll back a broken API deployment?"

  14. Answer: Redeploy the previous deployment to the stage.
  15. Trap: Deployments are immutable—you can’t edit them.

Key ⚠️ Trap Distinctions

Concept REST API HTTP API WebSocket API
Cost $$$ $ $$
Caching
Request Validation
IAM Auth
Use Case Enterprise APIs Internal microservices Real-time apps


7. ? Hands-On Challenge

Challenge:
Deploy a WebSocket API that echoes back any message sent to it (like a chat app). Use: - API Gateway (WebSocket) - Lambda (Python) - DynamoDB (to store connection IDs)

Solution:
1. Create a DynamoDB table (Connections) with connectionId as the primary key.
2. Create a Lambda function to handle $connect, $disconnect, and $default routes.
3. Deploy a WebSocket API with routes:
- $connect → Lambda (store connection ID in DynamoDB)
- $disconnect → Lambda (remove connection ID)
- $default → Lambda (echo message back to sender) 4. Test with wscat:
```bash
wscat -c wss://YOUR_API_ID.execute-api.us-east-1.amazonaws.com/prod


Hello
< Hello
```


Why it works:
- WebSocket APIs maintain persistent connections.
- DynamoDB stores active connections for broadcasting messages.


8. ? Rapid-Reference Crib Sheet

Command/Concept Example/Value Notes
Create REST API aws apigateway create-rest-api --name "MyAPI" Returns id (e.g., abc123).
Create HTTP API aws apigatewayv2 create-api --name "MyHTTPAPI" --protocol-type HTTP Cheaper than REST API.
Create WebSocket API aws apigatewayv2 create-api --name "MyWebSocketAPI" --protocol-type WEBSOCKET Use for real-time apps.
Enable Caching aws apigateway update-stage --rest-api-id abc123 --stage-name prod --patch-operations op=replace,path=/caching/enabled,value=true TTL: 0–3600s.
Enable CloudWatch Logs aws apigateway update-stage --rest-api-id abc123 --stage-name prod --patch-operations op=replace,path=/accessLogSettings/destinationArn,value=arn:aws:logs:... Logs go to /aws/api-gateway/....
Default Throttling 10,000 RPS (REST), 10,000 RPS (HTTP) Increase via AWS Support.
Lambda Proxy Integration --type AWS_PROXY Avoids manual request/response mapping.
Stage Variables ${stageVariables.LambdaArn} Use for environment-specific configs.
CORS Headers Access-Control-Allow-Origin: * Enable in API Gateway or Lambda.
WebSocket Routes $connect, $disconnect, $default Required for WebSocket APIs.
⚠️ API Gateway Timeout 29s (REST), 30s (HTTP) Lambda has a 15s timeout by default.
⚠️ WebSocket Max Message Size 128 KB Increase via AWS Support.


9. ? Where to Go Next

  1. AWS API Gateway Developer Guide – Official docs (bookmark this!).
  2. Serverless Stack (SST) Guide – Practical tutorials for API Gateway + Lambda.
  3. AWS Well-Architected Framework – Serverless – Best practices for API Gateway.
  4. API Gateway + Lambda + DynamoDB Workshop – Hands-on lab.

Final Tip:
API Gateway is the glue between your frontend and backend. Master it, and you’ll never expose a Lambda function directly to the internet again. ?



ADVERTISEMENT