Back to Blog

Amazon API Gateway for the AWS Developer Associate (DVA-C02): REST vs HTTP APIs, Integrations, Authorizers, Throttling & Stages

A developer-focused deep dive into Amazon API Gateway for the DVA-C02 exam: choosing between REST, HTTP, and WebSocket APIs, Lambda proxy vs custom integrations, IAM/Cognito/Lambda authorizers, throttling and usage plans, caching and CORS, stages and canary deployments, and the CloudWatch metrics that explain 4XX/5XX errors — with code, CLI, and the scenario clues the exam rewards.

By Sailor Team , July 28, 2026

Amazon API Gateway is the front door to almost every serverless application, and the DVA-C02 exam treats it that way. It threads through three of the four exam domains at once: it’s a core building block in Development with AWS Services (32% of the exam), a security boundary in the Security domain (26%), and a deployable artifact with stages and canaries in the Deployment domain (24%). You rarely get a question that says “configure API Gateway” in the abstract. Instead you get a scenario — a mobile app that needs token-based auth, a public API that’s getting hammered by one client, a Lambda that returns a 502 — and you have to know which API Gateway feature is the answer.

This guide covers API Gateway from a developer’s seat: the decisions the exam actually tests. We’ll work through choosing an API type, wiring integrations to Lambda without tripping over the proxy response shape, securing endpoints with the three authorizer options, protecting your backend with throttling and usage plans, and reading the CloudWatch metrics that turn a vague “the API is broken” into a specific fix. For the wider serverless picture this sits inside, keep the DVA-C02 serverless guide open alongside it, and anchor the whole syllabus with the Developer Associate exam guide for 2026.

What API Gateway Does — and What the Exam Tests

At its simplest, API Gateway accepts an HTTP request from a client, optionally authenticates and validates it, routes it to a backend (usually a Lambda function, but also an HTTP endpoint or another AWS service), transforms the request and response if needed, and returns the result. Around that flow it layers throttling, caching, monitoring, and versioning.

The exam doesn’t test you on clicking through the console. It tests decision points:

  • Which API type fits the requirements and budget?
  • Proxy or non-proxy integration — and why is my Lambda response coming back as a 502?
  • Which authorizer for token-based auth, for IAM users, for custom logic?
  • How do I stop one abusive client from throttling everyone else?
  • Which stage feature lets me ship 10% of traffic to a new version?

Everything below is organized around those questions.

REST API vs HTTP API vs WebSocket API

The first decision is the API type, and it’s a favorite exam question because the trade-offs are concrete. API Gateway offers three flavors.

FeatureREST APIHTTP APIWebSocket API
Primary useFull-featured request/response APIsLow-latency, low-cost request/responseReal-time, bidirectional (chat, live feeds)
Relative costHigher~70% cheaper than RESTPer-message + connection-minute
LatencyHigherLowerN/A
Lambda & HTTP proxyYesYesYes
Private integrationsYes (VPC Link, NLB)Yes (VPC Link, ALB/Cloud Map)Limited
AuthorizersIAM, Cognito, LambdaJWT (OIDC/OAuth), Lambda, IAMLambda (on $connect)
API keys & usage plansYesNoNo
Request/response mapping templates (VTL)YesNoNo
Request validationYesLimitedNo
CachingYes (stage-level)NoNo
WAF integrationYesNoNo

When to choose HTTP API

Reach for HTTP API when you want a straightforward proxy to Lambda or an HTTP backend at the lowest cost and latency. It’s the modern default for new serverless APIs that don’t need the heavier REST feature set. If a scenario emphasizes “cost-optimized,” “low latency,” or “simple proxy to Lambda” and doesn’t mention API keys, caching, or VTL transformations, HTTP API is almost always the intended answer.

When you still need REST API

Choose REST API when the requirements name a feature only it supports: API keys and usage plans (metering per customer), request/response mapping templates with VTL, stage-level caching, AWS WAF, or request validation against a model. Third-party monetized APIs — “sell access with a free and paid tier” — point straight at REST APIs with usage plans, because HTTP APIs have no API-key metering.

WebSocket APIs in brief

WebSocket APIs maintain a persistent, two-way connection. The exam expects you to recognize the use case (chat apps, live dashboards, multiplayer, streaming price updates) and the routing model: connections start at the $connect route, messages are dispatched by a route selection expression to routes like $default or custom actions, and you push messages back to a client via the @connections management API using its connectionId. You won’t configure one in depth, but “real-time bidirectional communication” is the phrase that selects WebSocket over REST/HTTP.

Integration Types: Connecting Your API to a Backend

An integration tells API Gateway where to send the request. The types you must know:

  • Lambda proxy — API Gateway passes the entire request to Lambda as a single event object and expects a specifically shaped response back. Minimal configuration; the function owns request parsing and response formatting.
  • Lambda (non-proxy / custom) — you use mapping templates to transform the request before it reaches Lambda and to transform Lambda’s output before it returns to the client. More control, more configuration.
  • HTTP proxy / HTTP — forward to any HTTP endpoint, proxy or custom.
  • AWS service — call another AWS service directly (e.g., drop a message into SQS or put an item in DynamoDB) with no Lambda in between.
  • Mock — return a response from API Gateway itself without a backend, useful for CORS preflight responses and stubbing.

The Lambda proxy response shape (a top exam trap)

With Lambda proxy integration, your function must return an object with the right structure, or API Gateway returns a 502 Bad Gateway. This is one of the most commonly tested API Gateway details on the DVA-C02:

exports.handler = async (event) => {
  // event contains: httpMethod, path, headers, queryStringParameters,
  // pathParameters, body (string), requestContext, isBase64Encoded, ...
  const name = event.queryStringParameters?.name ?? "world";

  return {
    statusCode: 200,
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    },
    body: JSON.stringify({ message: `Hello, ${name}` }), // body MUST be a string
    isBase64Encoded: false
  };
};

The classic failure: returning a plain object (return { message: "hi" }) instead of the { statusCode, body } envelope, with body as a JSON string. API Gateway can’t parse it and answers 502. If you see “Lambda works when I test it directly but the API returns 502,” the response shape is the near-certain cause. Contrast this with non-proxy integration, where a mapping template builds the client response from the raw Lambda output using Velocity Template Language (VTL) — more flexible, but you own the transformation.

AspectLambda proxyLambda non-proxy (custom)
Request to LambdaWhole request as one eventShaped by a mapping template
Response to clientLambda returns statusCode/body/headersBuilt by a mapping template from Lambda output
Config effortMinimalHigher (VTL templates)
FlexibilityFunction owns everythingFine-grained transform without code changes
Common error502 on malformed responseTemplate/$input mistakes

Mapping Templates, Stage Variables, and the Request Flow

For REST APIs using non-proxy integrations, a request passes through four phases: method request → integration request → integration response → method response. Mapping templates (VTL) live in the integration request and integration response, letting you reshape payloads, inject values, and select which fields pass through. You reference the incoming data with $input (e.g., $input.json('$'), $input.params('id')) and context with $context.

Stage variables are name–value pairs attached to a stage that act like environment variables for the API. A common pattern: point the integration at a Lambda alias using a stage variable, so dev invokes myFn:DEV and prod invokes myFn:PROD without redefining the method:

# Integration URI using a stage variable
arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/
  arn:aws:lambda:us-east-1:123456789012:function:myFn:${stageVariables.lambdaAlias}/invocations

That ties directly into Lambda versioning and aliases — reviewed in the serverless guide — and is a clean way to promote code through environments with one API definition.

Securing Your API: The Three Authorizer Options

Access control is where API Gateway shows up in the Security domain, and the exam wants you to match the authorizer to the scenario. There are three mechanisms plus resource policies.

AuthorizerHow it worksBest for
IAM authorizationCaller signs the request with SigV4; API Gateway checks IAM policyInternal service-to-service, or callers that already have AWS credentials
Cognito user poolClient sends a Cognito-issued JWT; API Gateway validates itWeb/mobile user sign-in and sign-up flows
Lambda authorizerYour Lambda inspects the token/request and returns an IAM policyCustom auth (third-party OIDC, opaque tokens, custom headers)

IAM authorization

With IAM auth, the client must sign requests with Signature Version 4 using AWS credentials, and you grant access via an IAM policy on the execute-api:Invoke action. This is the natural fit when one AWS service or an IAM-authenticated app calls your API — the same SigV4 signing covered in the SDK and request-signing guide. No user-facing login; the credentials do the talking.

Cognito user pool authorizers

When the requirement is “users sign up and log in from a mobile or web app,” the answer is a Cognito user pool authorizer. The app authenticates against the user pool, receives JWT tokens (ID and access), and sends the token in the Authorization header. API Gateway validates the token’s signature and expiry before the request reaches your backend — no custom code required. Cognito’s role across the exam is covered in the Developer Associate security guide.

Lambda authorizers (token vs request)

A Lambda authorizer (formerly “custom authorizer”) runs your own function to decide access. Two flavors:

  • Token-based (TOKEN) — receives the bearer token from a header (e.g., Authorization) and validates it.
  • Request-based (REQUEST) — receives the full request context (headers, query string, path, stage variables), for when the decision depends on more than a single token.

The function returns an IAM policy document (Allow/Deny on the method ARN) plus an optional principalId and a context object you can pass downstream. API Gateway caches the returned policy for a configurable TTL keyed on the token/identity source, so a hot API doesn’t invoke the authorizer on every call:

exports.handler = async (event) => {
  const token = event.authorizationToken; // TOKEN authorizer
  const effect = token === "allow-me" ? "Allow" : "Deny";
  return {
    principalId: "user123",
    policyDocument: {
      Version: "2012-10-17",
      Statement: [{
        Action: "execute-api:Invoke",
        Effect: effect,
        Resource: event.methodArn
      }]
    },
    context: { tier: "gold" } // available to the backend as $context.authorizer.tier
  };
};

API keys are not authentication

A frequent distractor: API keys are for identification and metering, not authentication. They tie a caller to a usage plan for throttling and quotas — they do not secure your API. If a question implies you can “secure the API with an API key,” that’s the wrong answer; pair API keys with a real authorizer.

Throttling, Usage Plans, and API Keys

API Gateway protects your backend with a token bucket algorithm defined by two numbers: a steady-state rate (requests per second) and a burst (bucket capacity for short spikes). When requests exceed the limit, callers get 429 Too Many Requests. Throttling applies at several levels, from broadest to narrowest:

  1. AWS account level — a default per-region limit across all your APIs (a soft limit you can raise).
  2. Stage level — default method throttling for a whole stage.
  3. Method level — override for a specific route.
  4. Usage plan / per-API-key — limits tied to an individual client.

The exam’s favorite scenario: “One customer’s traffic is throttling everyone. How do you limit just them?” The answer is a usage plan with per-key rate/burst limits and a quota (e.g., 10,000 requests/day), associated with that customer’s API key. Usage plans give you per-client throttling and metering — ideal for tiered/monetized APIs — and they’re REST API only. To require and meter a key, set the method’s API-key requirement and have clients send it in the x-api-key header.

Caching and CORS

Stage-level caching (REST APIs) stores backend responses for a configurable TTL, reducing calls to Lambda or your integration and cutting latency. Keys are derived from request parameters; you can mark parameters as cache keys and invalidate entries by sending the Cache-Control: max-age=0 header (requires InvalidateCache permission). Caching is a cost/latency lever — enable it for read-heavy endpoints with tolerable staleness.

CORS (Cross-Origin Resource Sharing) trips up many developers. A browser calling your API from a different origin sends a preflight OPTIONS request; your API must answer with Access-Control-Allow-Origin, -Headers, and -Methods. On HTTP APIs, CORS is a simple configuration toggle. On REST APIs, you typically enable CORS (which sets up a Mock integration for the OPTIONS method) and — critically for proxy integrations — also return the Access-Control-Allow-Origin header from your Lambda response, because proxy integrations don’t let API Gateway inject it for you. “Works in Postman, fails in the browser with a CORS error” is the tell.

Stages, Deployments, and Canary Releases

Changes to a REST API don’t go live until you create a deployment — an immutable snapshot of the API’s configuration — and associate it with a stage (e.g., dev, test, prod). Each stage has its own invoke URL, throttling, caching, logging, and stage variables. The mental model: a deployment is what, a stage is where it’s served.

For safe rollouts, API Gateway supports canary deployments on a stage: you route a percentage of traffic (say 10%) to a new deployment while the rest hits the current one, watch the metrics, then promote the canary to take 100% — or roll back by discarding it. This is the Deployment-domain feature to reach for when a question asks how to release an API change gradually with minimal blast radius. It complements the code-deployment strategies in the CI/CD deployment guide.

A minimal deploy from the CLI:

# Create a deployment and point the prod stage at it
aws apigateway create-deployment \
  --rest-api-id abc123 \
  --stage-name prod

# Configure a 10% canary on the prod stage
aws apigateway update-stage \
  --rest-api-id abc123 \
  --stage-name prod \
  --patch-operations op=replace,path=/canarySettings/percentTraffic,value=10

Monitoring and Troubleshooting API Gateway

When an API misbehaves, the fix starts with the right CloudWatch metric or log. This maps to the Troubleshooting and Optimization domain and to the diagnostic habits in the monitoring and troubleshooting guide.

Key CloudWatch metrics (per stage/method):

  • Count — total requests.
  • 4XXError — client errors (bad auth, throttling, malformed request).
  • 5XXError — backend/gateway errors.
  • Latency — total time API Gateway takes to respond.
  • IntegrationLatency — time spent waiting on the backend only. If Latency is high but IntegrationLatency is low, the overhead is in API Gateway (e.g., authorizer, mapping); if both are high, the backend is slow.

Two log types: execution logs (detailed per-request tracing you enable per stage, at ERROR or INFO level) and access logs (a customizable per-request record you route to CloudWatch Logs). Enable X-Ray active tracing on the stage to see the request path across API Gateway → Lambda → downstream services.

Common status codes and what they mean:

CodeTypical cause
403 ForbiddenMissing/invalid auth, authorizer denied, WAF block, or resource policy
429 Too Many RequestsThrottling — account, stage, method, or usage-plan limit hit
502 Bad GatewayMalformed Lambda proxy response (wrong shape, non-string body)
503 Service UnavailableBackend unavailable
504 Gateway TimeoutIntegration exceeded the timeout (default 29 seconds max for REST)

That 29-second integration timeout is exam-worthy: a long-running backend that overruns it returns 504. The fix is asynchronous processing — accept the request, hand it to SQS or Step Functions, and return immediately — a pattern from the event-driven applications guide.

Common DVA-C02 Scenarios and the Feature That Answers Them

Scenario clueFeature / answer
Lowest cost, low latency, simple Lambda proxyHTTP API
Sell tiered API access, meter per customerREST API + usage plans + API keys
Mobile users sign up / log inCognito user pool authorizer
Validate a third-party/opaque token with custom logicLambda authorizer (TOKEN)
Internal service-to-service, callers have AWS credsIAM authorization (SigV4)
One client is throttling everyonePer-key throttling via usage plan
Release an API change to 10% of traffic firstCanary deployment on the stage
Lambda works alone but API returns 502Fix Lambda proxy response shape
Browser CORS error, Postman worksEnable CORS + return Allow-Origin from proxy Lambda
Reduce repeated calls to a read-heavy backendStage-level caching
Backend takes >29s, returns 504Async pattern (SQS/Step Functions)
Real-time bidirectional messagingWebSocket API

Memorize the clue→feature mapping and a large fraction of API Gateway questions become pattern recognition. For the official specifics, the Amazon API Gateway Developer Guide is the authoritative reference.

Frequently Asked Questions

When should I pick an HTTP API over a REST API for the DVA-C02?

Default to HTTP API for cost-sensitive, low-latency proxies to Lambda or HTTP backends. Switch to REST API only when the requirements name a REST-only feature: API keys and usage plans, VTL mapping templates, stage caching, request validation, or AWS WAF. The exam signals the answer through those keywords, so read the requirements for cost/latency language versus feature language.

Why does my API return 502 when the Lambda function works?

With Lambda proxy integration, your function must return { statusCode, headers, body } where body is a string (usually JSON.stringify(...)). Returning a raw object or a non-string body makes API Gateway unable to parse the response, producing 502 Bad Gateway. Testing the function in the Lambda console bypasses this, which is why it “works” there but fails through the API.

What’s the difference between API keys and authorizers?

API keys identify and meter a caller for throttling and quotas via usage plans — they are not a security control. Authorizers authenticate and authorize requests (IAM SigV4, Cognito JWTs, or a Lambda authorizer returning an IAM policy). Secure the API with an authorizer; use API keys only for per-client metering and rate limiting.

Which authorizer should I use for a mobile app with user login?

A Cognito user pool authorizer. The app authenticates against the user pool and sends the returned JWT in the Authorization header; API Gateway validates it automatically. Use a Lambda authorizer instead only when you need custom logic — validating a third-party OIDC token, an opaque token, or a decision based on multiple request attributes.

How do I throttle just one abusive client without affecting others?

Create a usage plan with per-key rate, burst, and quota limits, associate it with that client’s API key, and require the key on the method. Because throttling then applies per key, one client hitting their limit gets 429 responses while everyone else is unaffected. Usage plans are a REST-API-only feature.

How do I roll out an API change gradually?

Use a canary deployment on the stage: route a small percentage of traffic (e.g., 10%) to the new deployment, monitor 4XXError, 5XXError, and latency in CloudWatch, then promote the canary to 100% or roll back. This limits blast radius and pairs well with the deployment strategies used for the Lambda and compute side of your app.

Conclusion

API Gateway earns its exam weight because it sits at the intersection of development, security, and deployment. Get comfortable with a handful of decisions and most questions resolve themselves: HTTP API for cheap, simple proxies; REST API when you need keys, caching, VTL, or WAF; Cognito for user login, Lambda authorizers for custom auth, IAM for signed service calls; usage plans to throttle per client; canary deployments to release safely; and the { statusCode, body } proxy shape to avoid the 502 trap. Wire those to the CloudWatch metrics — Latency versus IntegrationLatency, and the 4XX/5XX split — and you can diagnose a broken API instead of guessing.

The fastest way to make these patterns automatic is to see them in exam-weighted questions with explanations. Start free with the Developer Associate free resources and practice questions to get used to the scenario framing, and sequence the rest of your prep with the DVA-C02 study plan. When you want realistic, timed reps with a detailed rationale for every option, the Sailor.sh AWS Developer Associate (DVA-C02) Mock Exam Bundle runs eight full mock exams — including the API-type, authorizer, throttling, and 502/504 troubleshooting scenarios covered here — so you learn why each answer wins, not just that it does.

Limited Time Offer: Get 80% off all Mock Exam Bundles | Sale ends in 7 days. Start learning today.

Claim Now