Skip to content
Quest 07Intermediate15 min

Put an API in Front

Trainers don't call Lambda directly. They call a URL. API Gateway provides the front door: paths, methods, throttling and a stage name. CDK describes it with a few lines per route.

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 in event.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.

Create the API
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 addProxy or an ANY method: that sends every path and verb to one function and gives up per-route throttling, validation and authorization.
  • The same pokemon resource can hold more methods later (POST for new entries) without repeating the path.
GET /pokemon/{number}
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.
Tab inserts two spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the code.
Simulated — no AWS calls

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.

You want GET /pokemon/252 to reach the lookup function. Which construct chain is right?

Choose one answer.