How to Build a Serverless REST API with AWS CDK, Lambda, and API Gateway

Chizoba VictoryChizoba Victory
3 min read

Why Serverless for APIs?

Serverless architectures are transforming how we build scalable, cost-efficient APIs. In this guide, I’ll walk you through creating a REST API using AWS CDK, Lambda, and API Gateway—based on real-world patterns from my own project.

Serverless lets you focus on business logic, not infrastructure. With AWS Lambda and API Gateway, you only pay for what you use, and you get automatic scaling out of the box. Combined with AWS CDK (Cloud Development Kit), you can define your cloud resources as code, making deployments repeatable and version-controlled.


Project Overview & Architecture

Here’s what we’re building:

  • AWS API Gateway: Exposes REST endpoints.

  • AWS Lambda: Handles business logic.

  • Amazon DynamoDB: Stores data (for example, To Do items).

  • AWS CDK: Infrastructure as code.


1. Setting Up Your Project Structure

Organize your codebase for clarity and scalability. For example:

/lib
  video-api-stack.ts     # CDK stack definition
/resources
  allocatedResources.ts  # Resource allocation logic
/bin
  config.ts              # Environment/config logic
/lambda
  handler.ts             # Lambda function code

Initialize your CDK project:

npx cdk init app --language typescript

2. Writing the Lambda Function

Your Lambda function handles the API’s business logic. Example (lambda/handler.ts):

import { APIGatewayProxyHandler } from 'aws-lambda';

export const handler: APIGatewayProxyHandler = async (event) => {
  // Business logic here
  return {
    statusCode: 200,
    body: JSON.stringify({ message: 'Hello from Lambda!' }),
  };
};

3. Defining the API Gateway with CDK

In your CDK stack (lib/video-api-stack.ts):

import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';

const lambdaFunction = new lambda.Function(this, 'MyLambda', {
  runtime: lambda.Runtime.NODEJS_16_X,
  code: lambda.Code.fromAsset('lambda'),
  handler: 'handler.handler',
});

const api = new apigateway.RestApi(this, 'MyApi', {
  restApiName: 'Serverless API',
  description: 'This API serves Lambda endpoints',
});

const lambdaIntegration = new apigateway.LambdaIntegration(lambdaFunction);

api.root.addResource('hello').addMethod('GET', lambdaIntegration);

4. Integrating Lambda and API Gateway

  • Define resources and methods (e.g., /hello with GET).

  • Secure endpoints with custom authorizers if needed.

  • Use request validators for input validation.


5. Deploying the Stack

Configure your AWS credentials, then run:

cdk bootstrap
cdk deploy

CDK will provision your Lambda, API Gateway, and any other resources.


6. Testing the API

After deployment, CDK outputs your API endpoint. Test it with:

curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/hello

You should see

jsonCopyInsert{"message": "Hello from Lambda!"}

Best Practices & Lessons Learned

  • Use Infrastructure as Code: CDK makes your deployments repeatable.

  • Keep Lambda Single-Purpose: Each function should do one thing well.

  • Validate Inputs: Use API Gateway validators.

  • Automate Testing: Run unit and integration tests before deployment.

  • Secure Your API: Use IAM roles and custom authorizers.

Building serverless APIs with AWS CDK, Lambda, and API Gateway is powerful and scalable. By following these steps, you can quickly spin up production-grade APIs and focus on delivering value—not managing servers.


0
Subscribe to my newsletter

Read articles from Chizoba Victory directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chizoba Victory
Chizoba Victory