Deploy a Serverless API with AWS CDK and AWS Lambda
In this tutorial, we will implement a Serverless API using AWS Lambda and we will deploy it using AWS CDK.
In this tutorial, we will implement a Serverless API using AWS Lambda and we will deploy it using AWS CDK. We will use Typescript as the CDK language. It will be a page view counter where we will keep the state in Redis.
Check the github repo for the source code.
What is AWS CDK?
AWS CDK is an interesting project which allows you to provision and deploy AWS infrastructure with code. Currently TypeScript, JavaScript, Python, Java, C#/.Net are supported. You can compare AWS CDK with following technologies:
- AWS CloudFormation
- AWS SAM
- Serverless Framework
The above projects allows you to set up the infrastructure with configuration files (yaml, json) while with AWS CDK, you set up the resources with code. For more information about CDK see the related AWS Docs.
Project Setup
Install cdk with: npm install -g aws-cdk
Create a directory for your project. Inside the directory init cdk:
Counter Function Code
Create a directory for your API function
mkdir api
Inside the API folder, init and npm project and install ioredis.
In the api folder, create a file: counter.js
Counter Service
Go back to the top directory, install lambda and api-gateway libraries:
Inside the lib directory, create counter_service.ts:
You need to replace REPLACE_HERE with a proper Redis URL (ioredis format). You can create a Serverless Redis database in the Upstash for free. Copy the ioredis URL from Upstash console.
Update the Stack
Update lib/api-with-cdk-stack.ts
:
Deploy
In the top folder:
Now you should see the command outputs the endpoint url. Click to the url, you should see the page counter.
https://h9zf2bdye0.execute-api.eu-west-1.amazonaws.com/prod/
Success 🎉
Was this page helpful?