Lesson 1 of 7 Amazon API Gateway

Understanding Resources, Methods and Integrations in API Gateway

This lesson introduces how an API is built and called in Amazon API Gateway: the path a request takes, resources and methods in REST APIs, routes in HTTP APIs, the four stages of a REST method, the Lambda proxy contract and how an API is deployed. The later lessons in this module build on these ideas.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the steps API Gateway performs between receiving a request and returning a response.
  • Explain how resources, methods and path parameters define a REST API, and how routes define an HTTP API.
  • Describe the method request, integration request, integration response and method response stages.
  • Identify the event and response format that a Lambda proxy integration requires.
  • Explain why REST API changes need a deployment, and recognise the Missing Authentication Token response.

What happens to a request

Amazon API Gateway receives HTTPS requests from clients and passes each one to a backend, such as a Lambda function, an HTTP endpoint or another AWS service. On the way it can perform work that would otherwise be written into every backend, in the following order.

  1. The client sends the request to the API's endpoint over HTTPS.
  2. API Gateway matches the request's path and HTTP method to part of the API definition.
  3. It authorises the caller, for example with IAM, an Amazon Cognito user pool or a Lambda authorizer.
  4. It applies throttling limits and, for REST APIs, checks API keys and validates the request.
  5. It calls the backend through the configured integration, transforming the request if required.
  6. It returns the backend's response to the client, transforming it if required.

API Gateway is serverless: it scales with traffic, and it is charged per request received, with no charge when the API is idle. The rest of this lesson explains how the path and method in step 2 are defined and how the integration in step 5 works.

Resources and methods in REST APIs

A REST API is built from two kinds of element, each described below.

Resources

A resource is one segment of a URL path, arranged in a tree that starts at the root, /. A path parameter is written in braces: the resource /orders/{orderId} matches /orders/9017 and passes 9017 to the backend as orderId. A greedy path parameter, {proxy+}, matches every path below its parent, which lets one resource send all requests to a single backend that does its own routing.

Methods

A method is an HTTP verb, such as GET or POST, defined on a resource. The special method ANY matches every verb. Each method has its own settings: how callers are authorised, whether an API key is required, how the request is validated and which integration handles it. The following tree defines four operations on two resources:

/
└── /orders                 GET   (list orders)       POST  (create an order)
    └── /orders/{orderId}   GET   (read one order)    DELETE (cancel an order)

A request for a path or method that is not defined is rejected by API Gateway before any backend is called.

Routes in HTTP APIs

HTTP APIs use a simpler model. A route combines a method and a path in one expression, such as GET /orders/{orderId} or ANY /orders, and points to an integration. The special $default route catches every request that matches no other route, which suits an API that forwards all traffic to one backend. Path parameters and greedy parameters work as they do in REST APIs. The following table compares the two models.

ConceptREST APIHTTP API
Path and verbA method on a resourceA route, such as GET /orders
Catch-allA {proxy+} resource with ANYThe $default route
Releasing changesDeploy to a stageDeploy, or let the $default stage deploy automatically

How a request passes through a REST API method

Each REST API method processes a request in four stages. Understanding them explains where validation, transformation and error mapping take place.

  • Method request: declares what the client must send, such as required headers or query strings, the authoriser and the request model used for validation.
  • Integration request: says how to call the backend, including the backend's address, the HTTP method and any mapping template that reshapes the request.
  • Integration response: maps the backend's result to an HTTP status code, for example turning an error message from a function into a 400 response.
  • Method response: declares the status codes, headers and response models that the method can return to the client.

With a proxy integration, the integration request and integration response are pass-through: API Gateway sends the whole request to the backend and returns the backend's response unchanged, so the backend controls the status code and headers. With a non-proxy integration, the developer configures the mappings. Choosing an API Type, Endpoint and Integration compares the integration types, and Validating and Transforming Requests and Responses explains the mappings.

The following diagram shows the order in which a request and its response pass through the four stages.

The four stages of a REST API method. The method request checks the authorizer, required parameters and validation; the integration request calls the backend, optionally through a mapping template; the integration response maps the backend's result to a status code; and the method response declares what the client can receive. With a proxy integration, both integration stages pass the request and response through unchanged.
The request travels through the top row and the response through the bottom row. Validation and the authorizer run before the backend is called, so a rejected request never reaches it.
Put in order

The four stages of a REST method

Exam skills 1.1.4

Learn the order in which a REST API method handles a request and its response.

Log in to try this activity Interactive activities are free with an account.

The Lambda proxy contract

With a Lambda proxy integration, the function receives the HTTP request as its event and must return the HTTP response in a fixed format. The event contains the httpMethod, path, headers, queryStringParameters, pathParameters and the body, which is a string, together with a requestContext that describes the caller, such as the claims of an authorised user.

The function must return an object with a numeric statusCode, optional headers and a body that is a string. If it returns anything else, such as a body that is a JSON object, or if it raises an exception, API Gateway returns 502 Bad Gateway to the client and logs Malformed Lambda proxy response.

import json

def handler(event, context):
    order_id = event["pathParameters"]["orderId"]
    body = json.loads(event["body"] or "{}")            # the request body arrives as a string
    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({"orderId": order_id, "note": body.get("note")}),   # must be a string
    }

HTTP APIs use a newer event format, version 2.0, with fields such as routeKey, rawPath and requestContext.http.method. With this format, a function can also return a plain JSON object, which API Gateway sends as a 200 response. Code written for one format must be adapted for the other.

Scenario questions

Work with the Lambda proxy event

Exam skills 1.1.4 · 1.1.7

Practise reading the proxy event and predicting what the client receives.

Log in to try this activity Interactive activities are free with an account.

Deploying and calling an API

Changes to a REST API take effect only when the API is deployed to a stage, such as prod. Each stage has an invoke URL of the form https://{api-id}.execute-api.{region}.amazonaws.com/{stage}/ followed by the resource path. HTTP APIs usually use a $default stage with automatic deployment, whose URL has no stage name. Deploying APIs to Stages with Stage Variables, Canaries and Caching explains stages in depth.

API Gateway also needs permission to invoke a Lambda function. The console adds this to the function's resource-based policy automatically, but the AWS CLI, SDKs and some templates must add it explicitly, as Granting Permissions with Execution Roles and Resource-Based Policies explains. Two limits shape backend design: an integration must respond within 29 seconds by default, and a request or response payload can be at most 10 MB. The following commands create an HTTP API for an existing function with quick create, which adds a $default route and an automatically deployed stage, grant the permission and call the API:

API_ID=$(aws apigatewayv2 create-api --name orders-api --protocol-type HTTP \
    --target "$FUNCTION_ARN" --query ApiId --output text)

aws lambda add-permission --function-name orders-api --statement-id apigw-invoke \
    --action lambda:InvokeFunction --principal apigateway.amazonaws.com \
    --source-arn "arn:aws:execute-api:$AWS_REGION:$ACCOUNT_ID:$API_ID/*"

curl "https://$API_ID.execute-api.$AWS_REGION.amazonaws.com/orders/9017"
True or false

Deploying and calling an API

Exam skills 1.1.4 · 3.1.5

Check four facts about releasing and calling an API.

Log in to try this activity Interactive activities are free with an account.
Worked example

Missing Authentication Token

A developer adds a DELETE method to the /orders/{orderId} resource of a REST API and tests it straight away. The call returns 403 with the body {"message":"Missing Authentication Token"}, although the API does not use IAM authorisation and the GET method works.

Despite its wording, this response is what a REST API returns when a request matches no deployed resource and method. Three causes are common: the new method has been saved but not yet deployed to the stage, the URL omits or misspells the stage name, or the path or verb is wrong. Here the method had not been deployed. Deploying the API to the prod stage made the method available, and no change to authorisation was needed.

Check yourself

A function behind a Lambda proxy integration returns {"statusCode": 200, "body": {"ok": true}}. What does the client receive, and why?

Show answer

A 502 error. The proxy contract requires body to be a string, so API Gateway treats the response as malformed. The function must serialise the body, for example with json.dumps.

Exam Tips

Remember for the exam

  • A REST API is a tree of resources (path segments) with methods (HTTP verbs); an HTTP API uses routes such as GET /orders/{orderId} and a $default catch-all.
  • {proxy+} with ANY sends every path and verb to one backend.
  • A REST method has four stages: method request, integration request, integration response and method response; a proxy integration passes the request and response through unchanged.
  • A Lambda proxy response needs a numeric statusCode and a string body; anything else produces 502 and Malformed Lambda proxy response.
  • REST API changes are visible only after a deployment to a stage; the invoke URL includes the stage name.
  • 403 Missing Authentication Token from a REST API usually means the path, method or stage does not exist or has not been deployed.
  • API Gateway needs lambda:InvokeFunction in the function's resource-based policy, and integrations time out after 29 seconds by default.