You should explore the contents of this project. It demonstrates a CDK app with stacks:
dynamodbCdkStack
: Build dynamodb tablelambdaCdkStack
: Build lambda functionapiCdkStack
: Build api gateway
The cdk.json
file tells the CDK Toolkit how to execute your app.
- Node.js
- AWS CLI
- AWS CDK
- AWS Account
- Clone this repository
- Run the following commands:
cd aws-serverless-crud-api
npm install
- Configure your AWS credentials
- Copy
.env.example
to.env
and update the values cdk deploy --all
-> Deploy all stacks- Play with the API
cdk destroy --all
-> Destroy all stacks
GET /api/users
: Get all usersGET /api/users/{id}
: Get user by idPOST /api/users
: Create new userDELETE /api/users/{id}
: Delete user by idPUT /api/users/{id}
: Update user by id
const usersTable = new Table(this, 'usersTable', {
tableName: TableNames.USERS,
partitionKey: { name: 'id', type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
- Add a lambda handler in
src/handlers/user.ts
export const createUser = async (event: any): Promise<any> => {
const user = await userService.save(JSON.parse(event.body));
return { statusCode: 201, body: JSON.stringify(user) };
};
- Define a lambda function
const createUserFn = new NodejsFunction(this, 'createUserFn', {
functionName: 'createUserFn',
description: 'Create user',
entry: 'src/handlers/user.ts',
handler: 'createUser',
});
- Grant permission to access DynamoDB
usersTable.grantReadWriteData(createUserFn);
const restApi = new RestApi(this, 'userManagementRestApi', {
restApiName: 'User Management API',
description: 'User management REST API',
});
const users = apiRoot.addResource('users');
const createUserIntegration = new LambdaIntegration(createUserFn);
users.addMethod('POST', createUserIntegration);
npm run build
compile typescript to jsnpm run watch
watch for changes and compilenpm run test
perform the jest unit testscdk deploy
deploy this stack to your default AWS account/regioncdk diff
compare deployed stack with current statecdk synth
emits the synthesized CloudFormation template