Step 2: Simple API - solargis/cdk-workshop GitHub Wiki
In this step we will create simple API handled by Lambda function, which will return only hello message with current timestamp.
We will have simple web and simple API deployed in the cloud, but separated for now.
Fast-forward to this step (optional)
git checkout step-2/simple-api
npm install
NOTE: if you have uncommited work in project repository it is not possible to checkout new Git branch, you have 3 options:
git stash
- move all local changes into a 'drawer', more info heregit commit -a -m "my change"
- commit all changes to local branchgit reset --hard HEAD
- remove all local changes
Preparation
Add npm dependencies:
npm install --save @aws-cdk/aws-apigateway @aws-cdk/aws-lambda aws-lambda
npm install --save-dev @types/aws-lambda
2.1 Create simple API
Add Lambda handler code: ./lib/api/hello-lambda.ts
import { APIGatewayProxyEvent, Context, Callback } from 'aws-lambda';
export function handler(event: APIGatewayProxyEvent, context: Context, callback: Callback) {
console.log('*** hello ***', event);
callback(null, {
statusCode: 200,
body: JSON.stringify({ message: `Hello from CDK Lambda, ${Date.now()}` })
});
}
Add TypeScript config for API code: ./lib/tsconfig.api.json
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../dist/api",
"declaration": false
},
"include": ["api"],
"exclude": ["node_modules/**", "web*"]
}
Add build script for API: ./package.json
"scripts": {
"api:build": "tsc -p lib/tsconfig.api.json"
}
Build API code:
npm run api:build
- Check the compiled code in
./dist/api
Define cloud resources for API: ./cdk/cdk-workshop-stack.ts
import { LambdaIntegration, RestApi } from '@aws-cdk/aws-apigateway';
import { Code, Function, Runtime } from '@aws-cdk/aws-lambda';
// ...
// reference to compiled API code
const apiCode = Code.fromAsset('dist/api');
// Lambda handler definition
const helloHandler = new Function(this, 'HelloHandler', {
code: apiCode,
runtime: Runtime.NODEJS_10_X,
handler: 'hello-lambda.handler',
});
// API Gateway
const api = new RestApi(this, `CdkWorkshopAPI_${props.userName}`);
// API resource on /hello path
const helloApi = api.root.addResource('hello');
// GET /hello
helloApi.addMethod('GET', new LambdaIntegration(helloHandler));
Check stack changes:
cdk diff
Deploy simple API:
cdk deploy
Test
- Inspect Lambda in AWS Console: Services > Lambda
- Go to Monitoring > View logs in CloudWatch to inspect logs from lambda handler
- Create test event: Select a test event > Configure test events > Select template "Amazon API Gateway AWS Proxy"
- Run Lambda test in AWS Console