Back to Blog
Lesson 23 of the AWS: AWS Core Services for Developers course
Cloud NativeJuly 30, 20264 min read

Project Integration: Exposing the API with AWS CDK

Learn how to define API Gateway infrastructure in CDK to expose your Lambda backend. We’ll link your resources and deploy a production-ready API endpoint.

AWSCDKAPI GatewayLambdaInfrastructure as CodeServerless
Detailed view of a red circuit board with various electronic components and microchip.

Previously in this course, we explored API Gateway Routing and Integration: A Beginner’s Guide to understand how requests flow through AWS. Now, we’re moving from theory to production: you’ll use the AWS Cloud Development Kit (CDK) to define your API infrastructure, link it to the Lambda function we built in Project Integration: Saving App Data to DynamoDB with AWS CDK, and expose it as a live endpoint for your frontend.

API Deployment via CDK: First Principles

In a serverless architecture, API Gateway acts as the "front door." It accepts HTTP requests from your web client, translates them, and triggers your Lambda function. By defining this in CDK, you ensure your infrastructure is repeatable, version-controlled, and documented.

The key components we need to define are:

  1. RestApi: The top-level container for your API.
  2. Resource: A path in your URL (e.g., /items).
  3. Method: The HTTP verb allowed on that path (e.g., POST or GET).
  4. LambdaIntegration: The glue that connects the API method to your code.

Worked Example: Defining the Gateway

Open your CDK stack file (usually found in lib/your-project-stack.ts). We will define a LambdaRestApi, which is a high-level construct that handles the boilerplate of creating a Gateway and connecting it to your Lambda in one block of code.

TYPESCRIPT
import * as cdk from CE9178">'aws-cdk-lib';
import { Construct } from CE9178">'constructs';
import * as lambda from CE9178">'aws-cdk-lib/aws-lambda';
import * as apigateway from CE9178">'aws-cdk-lib/aws-apigateway';

export class MyWebAppStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Assume your Lambda is already defined here as CE9178">'myLambda'
    const myLambda = new lambda.Function(this, CE9178">'MyBackendHandler', {
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: CE9178">'index.handler',
      code: lambda.Code.fromAsset(CE9178">'lambda'),
    });

    // Define the API Gateway linked to your Lambda
    const api = new apigateway.LambdaRestApi(this, CE9178">'MyWebAppApi', {
      handler: myLambda,
      proxy: true, // This routes all requests to the Lambda
      deployOptions: {
        stageName: CE9178">'prod',
      },
    });

    // Output the API URL so you can find it easily
    new cdk.CfnOutput(this, CE9178">'ApiUrl', {
      value: api.url,
      description: CE9178">'The URL of your deployed API',
    });
  }
}

By setting proxy: true, you tell API Gateway to pass the entire request object (headers, body, path) directly to your Lambda code. This is the simplest way to get started, as it allows your backend code to handle routing logic internally.

Hands-on Exercise: Deploy Your Endpoint

  1. Update your stack: Add the LambdaRestApi code shown above to your existing stack definition.
  2. Synthesize and Deploy: Run cdk synth to verify the CloudFormation template, then execute cdk deploy.
  3. Verify: Once the deployment finishes, look at your terminal output. You should see a line starting with MyWebAppStack.ApiUrl = https://....
  4. Test: Copy that URL and use curl or a tool like Postman to send a POST request to it. Ensure your Lambda logic returns a success response.

Common Pitfalls

  • Missing Permissions: While LambdaRestApi automatically adds the necessary IAM permissions for the API to invoke the Lambda, manual configurations often forget this. Always check your IAM roles if you get a 403 Forbidden error.
  • Stage Name Confusion: By default, API Gateway might create a prod stage, but if you don't explicitly name it in deployOptions, you might end up with a URL that includes /dev/ or no stage at all.
  • Cold Starts: Your first request might be slightly slower because AWS is "warming up" your Lambda container. This is normal behavior for serverless applications.

Frequently Asked Questions

Q: Why use LambdaRestApi instead of RestApi? A: LambdaRestApi is a "construct" that bundles the API, the resource, and the integration into one class. It's faster for simple, single-function backends.

Q: Can I change the URL path later? A: Yes, but it will trigger a redeployment of the API Gateway. Always be careful with production URLs.

Q: What if I need to handle different paths (e.g., /users vs /orders)? A: You would set proxy: false and define individual Resource and Method objects in your CDK stack to map specific paths to specific Lambda functions.

Recap

We have successfully moved from raw infrastructure definition to exposing a public-facing API. By using LambdaRestApi, we effectively linked our backend logic to the outside world, creating a robust, managed entry point for our web app. You now have a live URL that triggers your serverless code.

Up next: Deploying a Static Frontend: Hosting and CDN Integration

Similar Posts