What you'll learn
- A REST API is built from resources (path segments), methods (GET, POST …) and integrations (what answers).
- A
{number}segment is a path parameter. Lambda receives it inevent.pathParameters(in a Python handler,event["pathParameters"]). - CDK creates the deployment, the stage and the permission for API Gateway to invoke the function. You write none of that.
Section 01
A REST API
apigw.RestApi creates the API; deployOptions configures the stage. The default stage is prod; many teams name it after the API version instead, here v1.
import * as apigw from "aws-cdk-lib/aws-apigateway";
const api = new apigw.RestApi(this, "PokedexApi", {
deployOptions: { stageName: "v1" },
});Section 02
Resources and methods
api.root is the / resource. addResource adds one path segment, and addMethod attaches a verb with an integration. A LambdaIntegration calls the function in proxy mode: API Gateway passes the whole request in, and the function returns the status code and body.
- Don't reach for
addProxyor anANYmethod: that sends every path and verb to one function and gives up per-route throttling, validation and authorization. - The same
pokemonresource can hold more methods later (POSTfor new entries) without repeating the path.
api.root
.addResource("pokemon")
.addResource("{number}")
.addMethod("GET", new apigw.LambdaIntegration(lookupFn));Section 03
What CDK adds for you
Check the exercise output: besides AWS::ApiGateway::RestApi, Resource and Method, CDK adds a Deployment, a Stage and AWS::Lambda::Permission resources. Without the permission, API Gateway can't invoke the function and callers get a 500 “Internal server error”, a classic hand-written-template bug. The integration makes it for you, one for the test console and one for real traffic.
Practice
Your turn
Expose the lookup function as GET /pokemon/{number}. Create the API with the stage name v1, add a pokemon resource with a {number} child, and attach a Lambda integration to its GET method. Use explicit routes, not a proxy (ANY).
stageName: "v1" and GET /pokemon/{number} routed to lookupFn with a LambdaIntegration.The simulator runs the constructs this course teaches, plus simple loops and helper methods. Other CDK code may not be recognised.
Check
Check your understanding
Quick Quiz · one question, as many tries as you need.
GET /pokemon/252 to reach the lookup function. Which construct chain is right?Choose one answer.