Choosing an API Type, Endpoint and Integration
This lesson explains how to choose between REST, HTTP and WebSocket APIs, which endpoint type to deploy, and how each request reaches the backend. The API type decides which features are available, and the integration type decides how much API Gateway changes the request on the way.
Learning outcomes
After completing this lesson, you will be able to:
- Choose between REST, HTTP and WebSocket APIs from the features a scenario requires.
- Distinguish edge-optimized, Regional and private endpoint types.
- Distinguish proxy and non-proxy integrations and the response format a Lambda proxy integration must return.
- Diagnose common API Gateway errors, such as 502 and 504 responses, from their causes.
Choosing an API type
API Gateway offers three types of API, and the type is chosen when the API is created, so the choice should follow from the features the API needs.
A REST API is the most capable type. It supports API keys and usage plans for per-client throttling and quotas, request validation, response caching, mapping templates that transform requests and responses, AWS WAF, resource policies and private endpoints reachable only from a VPC. An HTTP API is a simpler, faster and cheaper type for APIs that mainly proxy requests to Lambda or an HTTP backend. It includes a built-in JWT authorizer for tokens from Cognito or any OpenID Connect provider, but lacks API keys, usage plans, caching, request validation and AWS WAF. A WebSocket API keeps a persistent two-way connection with each client, so the server can push messages, which suits chat applications, notifications and live dashboards.
The following table summarises the three types.
| API type | Best for | Key features |
|---|---|---|
| REST API | APIs that need full API management | Usage plans and API keys, request validation, caching, AWS WAF, private endpoints |
| HTTP API | Simple, low-cost, low-latency APIs | Built-in JWT authorizers; cheaper and faster, but fewer features |
| WebSocket API | Real-time two-way apps such as chat or live dashboards | Persistent connections; messages routed by their content |
If a scenario needs caching, API keys or request validation, the answer is a REST API.
Endpoint types
A REST API is deployed with one of three endpoint types, which decide where clients connect and who can reach the API. HTTP APIs and WebSocket APIs are always Regional.
An edge-optimized endpoint places a CloudFront distribution, managed by API Gateway, in front of the API. Clients connect to the nearest CloudFront edge location, and the request travels to the API's Region over the AWS network, which reduces latency for clients spread around the world. The distribution is not visible in your account and cannot be configured. A Regional endpoint is served directly from the API's Region. It suits clients in or near that Region, such as other services in the same Region, and it is the type to choose when you want to place your own CloudFront distribution in front of the API to control caching or attach AWS WAF at the edge. A private endpoint is reachable only through an interface VPC endpoint for API Gateway, so the API is never exposed to the internet; a resource policy must allow access from the chosen VPCs or VPC endpoints.
The following table summarises the three endpoint types.
| Endpoint type | Served from | Use when |
|---|---|---|
| Edge-optimized | A CloudFront distribution managed by API Gateway | Clients are spread around the world |
| Regional | The API's own Region | Clients are in the same Region, or you want your own CloudFront distribution in front |
| Private | Interface VPC endpoints only | The API must be reachable only from inside your VPCs |
Integration types
The integration connects a method, such as GET /orders/{id}, to the backend that handles it. The main distinction is between proxy integrations, which pass the request through unchanged, and non-proxy integrations, which let API Gateway transform it.
With a Lambda proxy integration, API Gateway sends the whole HTTP request, including the path, headers, query string and body, to the function as one event, and the function must return the complete response. This is the simplest and most common choice. A Lambda custom integration uses mapping templates to build the event the function receives and to reshape its result, so the function can be unaware of HTTP. HTTP integrations forward requests to any HTTP endpoint, either unchanged or with mapping templates.
An AWS service integration calls an AWS API directly, for example SendMessage on an SQS queue or StartExecution on a Step Functions state machine. Removing a Lambda function that would only forward the request reduces cost, latency and code to maintain; API Gateway calls the service with an IAM role that you provide. A private integration uses a VPC link to reach a load balancer inside a VPC, so backends need not be public. A mock integration returns a fixed response without calling any backend.
The following table summarises the integration types.
| Integration | What it does |
|---|---|
| Lambda proxy | Passes the whole HTTP request to a function; the function builds the full response |
| Lambda custom (non-proxy) | Mapping templates reshape the request and response around the function |
| HTTP | Forwards the request to any HTTP endpoint |
| AWS service | Calls a service directly, such as sending to SQS or starting a Step Functions execution, with no Lambda in between |
| Private (VPC link) | Reaches resources inside a VPC through a Network or Application Load Balancer |
| Mock | Returns a fixed response with no backend |
The Lambda proxy response format
With a proxy integration the function must return a statusCode, optional headers and a string body. Returning anything else, such as an unserialised dictionary, makes API Gateway answer 502 Bad Gateway with "Malformed Lambda proxy response".
import json
def handler(event, context):
order_id = event["pathParameters"]["id"]
return {
"statusCode": 200,
"headers": {"Content-Type": "application/json", "Access-Control-Allow-Origin": "https://app.example.com"},
"body": json.dumps({"id": order_id, "status": "SHIPPED"}),
}WebSocket APIs
A WebSocket API keeps a persistent connection open between the client and API Gateway, so the backend can push messages to clients without polling. API Gateway selects a route for each message by evaluating a route selection expression, such as $request.body.action, and three predefined routes handle the connection's lifecycle. The following table describes them.
| Route | When it runs | Typical use |
|---|---|---|
$connect | A client opens a connection | Authorise the client and store its connection ID |
$disconnect | The connection closes | Remove the connection ID from storage |
$default | No other route matches the message | Handle unrecognised actions |
Each connection has a connection ID. Because Lambda functions are stateless and run in many execution environments, connection IDs are stored in a shared store such as DynamoDB. To send a message to a client, the backend calls the PostToConnection operation of the API Gateway Management API on the @connections endpoint, which requires the execute-api:ManageConnections permission. A route's response is returned only to the client that sent the message, so broadcasting to a chat room means calling PostToConnection for each stored connection.
import boto3
client = boto3.client(
"apigatewaymanagementapi",
endpoint_url="https://a1b2c3d4e5.execute-api.eu-west-1.amazonaws.com/prod",
)
def broadcast(connection_ids, message):
for connection_id in connection_ids:
try:
client.post_to_connection(ConnectionId=connection_id, Data=message.encode())
except client.exceptions.GoneException:
remove_connection(connection_id) # the client disconnected; delete the stale IDTimeouts and common errors
The integration timeout is 29 seconds by default. For Regional and private REST APIs it can be raised through a quota request, at the cost of some account-level throttle capacity. Work that takes longer belongs in an asynchronous design, for example accepting the request, placing it on a queue and returning a job ID that the client checks later.
Three status codes appear frequently in exam scenarios, and each points to a different part of the request path. A 502 Bad Gateway means API Gateway reached the backend but could not use its answer; with Lambda proxy integrations, it almost always means the function returned a response in the wrong format or failed with an unhandled error. A 504 Gateway Timeout means the backend did not answer within the integration timeout, so the cause is a slow backend or a network path that never connects, such as a VPC function with no route to its dependency. A 429 Too Many Requests means API Gateway throttled the request before it reached the backend, because an account, stage, method or usage plan limit was exceeded; clients should retry with exponential backoff.
The following table summarises these errors.
| Status code | Usual cause |
|---|---|
502 Bad Gateway | The backend returned a badly formatted response, often a malformed Lambda proxy response |
504 Gateway Timeout | The integration did not respond within the timeout |
429 Too Many Requests | The request was throttled |
Decoding API Gateway errors
A mobile team reports a mix of errors from the same API. Each status code points to a different cause:
| Error | Most likely cause | Fix |
|---|---|---|
502 Bad Gateway | The Lambda proxy integration returned a malformed response (no statusCode or a non-string body) | Return {"statusCode": 200, "body": json.dumps(...)} |
504 Gateway Timeout | The integration took longer than the integration timeout (29 s by default) | Make the work asynchronous, or raise the timeout on Regional APIs if justified |
403 Forbidden with "Missing Authentication Token" | Wrong path or method, or the API was not deployed | Check the URL, stage and deployment |
429 Too Many Requests | Throttling by stage, method or usage plan | Back off and retry; raise limits |
The 502 turned out to be a function returning a Python dictionary as the body. With proxy integration, API Gateway passes the function's response straight through, so it must already be in the exact shape API Gateway expects.
A Lambda proxy integration returns a plain string instead of an object with statusCode and body. What does the client receive?
Show answer
A 502 Bad Gateway error, because API Gateway cannot turn a malformed proxy response into an HTTP response.
Exam Tips
Remember for the exam
- A
502from a Lambda proxy integration usually means the function returned a badly formatted response. - A
504means the integration exceeded its timeout. - Caching, API keys or request validation call for a REST API, not an HTTP API.
- To send requests straight to SQS or Step Functions without Lambda, use an AWS service integration.
- An API reachable only from inside your VPCs is a private REST API with an interface endpoint.
- To push messages to WebSocket clients, store connection IDs in DynamoDB and call
PostToConnection.