Sub topic 1
How an HTTP API Works: Routes, Integrations, and Stages
Prerequisites
Assume basic HTTP, JSON, Python, the AWS CLI, and IAM roles. An IAM role is a set of permissions that a service can use.
How the pieces fit
An API Gateway HTTP API accepts an HTTP request and matches it to a route, which combines an HTTP method and path, such as GET /items/{id}. The route connects to an integration, the backend that handles the request. A common integration is an AWS Lambda function.
A stage is a named deployment of an API. For example, dev and prod can point to different configurations or versions. A stage URL commonly looks like:
https://api-id.execute-api.region.amazonaws.com/stage
HTTP API or REST API
HTTP APIs usually cost less and have lower latency. Choose one when you need standard routing, Lambda or HTTP integrations, JWT authorization, and CORS.
REST APIs provide more features, including usage plans, API keys, request validation, and some advanced mapping and management options. Choose REST when those features are requirements.
| Requirement | Typical choice |
|---|---|
| Low-cost API with common features | HTTP API |
| API keys and usage plans | REST API |
Lambda essentials for API backends
A Lambda function runs a handler when invoked. The handler receives an event, which contains request data, and a context, which contains invocation metadata. Its execution role controls access to AWS services.
With a Lambda proxy integration, API Gateway passes the request to Lambda with little transformation. Lambda must return an HTTP-compatible object containing a status code, headers, and a string body.
import json
def handler(event, context):
item_id = event["pathParameters"]["id"]
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"id": item_id}),
}Designing routes and path parameters
Use nouns for resources and HTTP methods for actions:
GET /itemslists items.GET /items/{id}retrieves one item.POST /itemscreates an item.
{id} is a path parameter. In a version 2.0 event, its value is available at event["pathParameters"]["id"]. Keep route patterns specific, and use a $default route only for deliberate catch-all behavior.
Exercise
Which route retrieves item 42?
Show answer
Send GET /items/42. API Gateway matches {id} and passes "42" as the path parameter.