Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 70 ยท Serverless and messaging

API Gateway and Function URLs

Learn API Gateway: REST vs HTTP APIs, routes, stages, authorizers, throttling and Lambda proxy integration, plus Function URLs, with runnable emulators.

A Lambda function has no web address of its own. To let a browser, a mobile app or another company call it over HTTPS, you put something in front of it that accepts HTTP requests and turns each one into a function invocation. The main service for this is Amazon API Gateway. It handles routing, authentication, rate limiting, TLS and monitoring, so your function only contains business logic.

This lesson builds on Lambda Functions. You will learn the two kinds of API (REST and HTTP), how routes and stages work, what the Lambda proxy event looks like, and when a plain Function URL is enough. Runnable stand-ins let you try route matching, proxy events and throttling.

API Gateway cannot run on this site, and there is no AWS account here. The CLI commands and JSON are read-only. The runnable examples are small Python models of the same ideas, simplified: they do not do real HTTP, TLS or exact AWS limits.

The request path

flowchart LR
    Client["Client<br/>browser or app"] -->|"HTTPS"| APIGW["API Gateway<br/>route, authorize, throttle"]
    APIGW -->|"proxy event"| Fn["Lambda function"]
    Fn -->|"statusCode, headers, body"| APIGW
    APIGW -->|"HTTP response"| Client

API Gateway turns an HTTP request into an event and the function's return value back into an HTTP response.

REST APIs and HTTP APIs

API Gateway offers two main HTTP products, plus WebSocket APIs for two-way messaging.

HTTP API REST API
Price Lower (roughly a third of REST per million requests) Higher
Latency Lower overhead Slightly higher
Authorizers JWT (for example Amazon Cognito), Lambda, IAM Cognito, Lambda, IAM
API keys and usage plans No Yes
Request validation, caching, WAF Not built in Yes
Stage setup A $default stage can deploy automatically Explicit deployments to named stages

The simple rule: start with an HTTP API and move to REST only when you need its extra features, such as per-customer usage plans with API keys, request validation, built-in response caching or a direct AWS WAF attachment. Prices change, so confirm them on the pricing page.

Routes, integrations and stages

A route is a method plus a path pattern, such as GET /items/{id}. An integration says what happens when a route matches, most often "invoke this Lambda function". Path patterns can contain:

  • Literal segments: /items.
  • Parameters: /items/{id} matches /items/42 and sets id to 42.
  • Greedy parameters: /files/{proxy+} matches /files/a/b/c.txt.
  • ANY as a method, and a $default route that catches everything else.

When several routes match, the most specific one wins: a literal beats a parameter, which beats a greedy one.

A stage is a named deployment of the API, such as dev or prod, with its own URL path (.../prod/items), settings and throttling. The base URL looks like https://abc123.execute-api.eu-west-1.amazonaws.com/prod. You can attach your own domain name through a custom domain mapping (with an ACM certificate and a Route 53 alias).

Creating a quick HTTP API that points at an existing function is a single command (read-only here):

Terminal
aws apigatewayv2 create-api \
  --name shop-api \
  --protocol-type HTTP \
  --target arn:aws:lambda:eu-west-1:123456789012:function:shop-handler

Route matching you can run

This model implements the specificity rule. Each segment of a route gets a score (literal 3, parameter 2, greedy 1), and the highest-scoring match wins, with $default as the last resort.

Python Route matching with parameters and greedy paths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

/items/special matches both GET /items/special and GET /items/{id}, and the literal route wins. DELETE /items matches no specific route, so it falls through to $default. In a real API without a $default route, that request would get a 404 Not Found.

Lambda proxy integration

With proxy integration, API Gateway passes the whole request to your function as one event and expects one response object in return. You do not map fields yourself. For HTTP APIs the event uses payload format 2.0; REST APIs use an older format 1.0 with similar content under different names (httpMethod, path, multiValueHeaders).

A shortened 2.0 event for GET /items/42?verbose=true:

JSON
{
  "version": "2.0",
  "routeKey": "GET /items/{id}",
  "rawPath": "/items/42",
  "rawQueryString": "verbose=true",
  "headers": { "accept": "application/json" },
  "queryStringParameters": { "verbose": "true" },
  "pathParameters": { "id": "42" },
  "requestContext": {
    "http": { "method": "GET", "path": "/items/42", "sourceIp": "203.0.113.9" },
    "stage": "$default",
    "requestId": "req-1"
  },
  "body": null,
  "isBase64Encoded": false
}

Your function answers with a dictionary that API Gateway converts to an HTTP response:

Python
def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "headers": {"content-type": "application/json"},
        "body": '{"id": "42"}',
    }

The body must be a string, so JSON has to be serialized first. If a function raises an exception or returns something API Gateway cannot understand, the client receives a 5xx error, for example 502 Bad Gateway for a malformed response on a REST API.

Python Build a proxy event and return an HTTP response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same function handled five requests and chose the status code each time: 200, 404, 201, 400, and then 200 for the order created in between. In real code you would also handle isBase64Encoded for binary bodies and add CORS headers if a browser on another origin calls the API.

Authorizers

An authorizer decides whether a request may reach your integration at all, before your function runs:

  • IAM authorization: the caller signs the request with AWS credentials (see IAM). Good for service-to-service calls.
  • JWT authorizer (HTTP API) or Cognito user pool authorizer (REST): API Gateway validates a token from an identity provider and rejects invalid or expired ones.
  • Lambda authorizer: your own function receives the token or headers and returns allow or deny (and context to pass on). Flexible, with results cached for a while to save invocations.

A rejected request gets 401 Unauthorized or 403 Forbidden without invoking your backend.

Throttling

API Gateway protects your backend with token-bucket throttling: a rate (steady requests per second) and a burst (how many requests can be absorbed at once). The account has default regional limits (on the order of 10,000 requests per second with a burst of 5,000, subject to change), and you can set lower limits per stage or per route. Requests over the limit receive 429 Too Many Requests. REST APIs add usage plans that give each API key its own quota.

Python A token-bucket throttle: rate and burst

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The burst of five absorbs the first five of the eight simultaneous requests, and the last three get 429. Afterwards tokens refill at two per second, so requests that come every 250 ms are accepted only about every other time. Well-behaved clients retry 429 with exponential backoff.

Function URLs

For a simple case you can skip API Gateway entirely. A Function URL gives a function its own dedicated HTTPS endpoint of the form https://<url-id>.lambda-url.<region>.on.aws. It uses the same payload format 2.0 and costs nothing beyond the normal Lambda charges. Authentication is either NONE (public) or AWS_IAM (signed requests), and you can configure CORS on the URL.

Terminal
aws lambda create-function-url-config \
  --function-name shop-handler \
  --auth-type AWS_IAM

Function URLs are a good fit for webhooks, internal tools and prototypes. They have no routing (your code reads rawPath), no usage plans, no custom authorizers and no built-in throttling per client. When you need those, use API Gateway.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which API Gateway type should you normally start with for a simple Lambda-backed API?

    HTTP APIs cost less and have less overhead. Move to REST APIs when you need API keys with usage plans, request validation or built-in caching.
  2. 2. Two routes match the request GET /items/special - "GET /items/special" and "GET /items/{id}". Which one is used?

    A literal segment beats a parameter, which beats a greedy parameter.
  3. 3. In Lambda proxy integration, what must the function's response body be?

    The response object contains statusCode, headers and a body string. JSON data has to be converted with json.dumps.
  4. 4. What does a client receive when it exceeds a configured throttling limit?

    Throttled requests are rejected with 429, and clients should retry later with backoff.
  5. 5. When is a Function URL a reasonable choice instead of API Gateway?

    Function URLs are simple and free. You give up routing, usage plans, authorizers and per-client throttling.

Summary

  • API Gateway turns HTTP requests into Lambda invocations and function results back into responses, handling routing, authorization and throttling.
  • Prefer HTTP APIs for simple, cheap APIs; choose REST APIs for API keys with usage plans, validation and caching.
  • Routes pair a method with a path pattern; the most specific match wins, and $default catches the rest. Stages are named deployments.
  • Proxy integration sends the full request as an event (payload 2.0 for HTTP APIs) and expects statusCode, headers and a string body back.
  • Authorizers (IAM, JWT or Cognito, Lambda) run before your code; throttling returns 429 when the rate or burst is exceeded.
  • A Function URL is a free, simple HTTPS endpoint for one function without gateway features.

Next: SQS, SNS and Fan-Out