Build Your First Serverless App with AWS CDK: A Step-by-Step Guide
Discover how to use the AWS Cloud Development Kit (CDK) to define your cloud infrastructure using familiar programming languages. This guide walks you through deploying a simple serverless API using AWS Lambda and Amazon API Gateway.
Moving Beyond ClickOps with AWS CDK
When you first start with Amazon Web Services, the AWS Management Console is a great place to explore. However, as your applications grow, manually clicking through the console—often called "ClickOps"—becomes difficult to track, scale, and replicate.
Enter the AWS Cloud Development Kit (CDK).
AWS CDK is an open-source software development framework that lets you define your cloud application infrastructure using familiar programming languages like TypeScript, Python, Java, and C#. Under the hood, CDK compiles your code into AWS CloudFormation templates.
In this guide, we will build a simple Serverless API using AWS Lambda and Amazon API Gateway with TypeScript.
Prerequisites
Before we dive into the code, ensure you have the following installed and configured on your local machine:
Node.js (v14.15.0 or later)
AWS CLI configured with your credentials
AWS CDK CLI (install globally via npm install -g aws-cdk)
Step 1: Initialize Your CDK Project
First, let's create a new directory for our project and initialize a standard CDK app using TypeScript.
Bash
mkdir my-serverless-api
cd my-serverless-api
cdk init app --language typescript
This command generates a structured project complete with a lib folder (where your infrastructure code lives) and a bin folder (the entry point of your CDK app).
Step 2: Write Your Infrastructure Code
Navigate to the lib/my-serverless-api-stack.ts file. This is where we will define our AWS resources. We need two main components: a Lambda function to process requests, and an API Gateway to route HTTP traffic to that function.
First, install the necessary AWS constructs:
Bash
npm install aws-cdk-lib
Next, update your stack file:
TypeScript
import * as cdk from 'aws-cdk-lib';import { Construct } from 'constructs';import * as lambda from 'aws-cdk-lib/aws-lambda';import * as apigateway from 'aws-cdk-lib/aws-apigateway';export class MyServerlessApiStack extends cdk.Stack {constructor(scope: Construct, id: string, props?: cdk.StackProps) {super(scope, id, props);// 1. Define the AWS Lambda Functionconst helloFunction = new lambda.Function(this, 'HelloHandler', { runtime: lambda.Runtime.NODEJS_18_X, code: lambda.Code.fromInline(` exports.handler = async function(event) { return { statusCode: 200, body: JSON.stringify('Hello from AWS CDK!'), }; }; `), handler: 'index.handler',});
// 2. Define the API Gateway to route requests to the Lambdanew apigateway.LambdaRestApi(this, 'Endpoint', { handler: helloFunction,});}
}
Note: For production applications, you would typically store your Lambda code in a separate directory rather than using Code.fromInline(). We are using inline code here for the sake of simplicity.
Step 3: Bootstrap and Deploy
Before you can deploy a CDK app into an AWS environment (account and region) for the first time, you must install a "bootstrap stack." This provisions resources like an S3 bucket for storing deployment assets.
Bash
cdk bootstrap
Once bootstrapped, deploy your application to the cloud!
Bash
cdk deploy
The CLI will prompt you to confirm the creation of security-related resources (like IAM roles for your Lambda function). Type y and hit Enter.
Step 4: Test Your New API
After a successful deployment, the CDK CLI will output a green checkmark along with your new API Gateway Endpoint URL. It will look something like this:
Outputs:
MyServerlessApiStack.Endpoint8024A810 = https://xyz123.execute-api.us-east-1.amazonaws.com/prod/
Click the link or use curl in your terminal to test it:
Bash
curl https://xyz123.execute-api.us-east-1.amazonaws.com/prod/
You should see the response: "Hello from AWS CDK!"
Conclusion Congratulations! You've just provisioned a fully functional, serverless API using Infrastructure as Code. By writing infrastructure in the same language as your application logic, you can leverage your existing tools, testing frameworks, and version control workflows.
Keep building, and happy coding!
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article