Building a More Complex Serverless Application with AWS Lambda and API Gateway Using TypeScript
Welcome to our journey into the world of serverless applications with AWS Lambda and API Gateway! Today, we’re diving into a more complex example using TypeScript, a language choice that brings type safety and other modern features to our serverless architecture. This step-by-step guide will walk you through creating a Lambda function in TypeScript that interacts with an external API and returns processed data through API Gateway.
Prerequisites
Before we start, make sure you have the following:
An AWS account
Node.js and npm installed
The AWS CLI configured with appropriate permissions
Step 1: Setting Up Your TypeScript Environment
First, we need to set up a TypeScript environment for our Lambda function. This involves initializing a new Node.js project and adding the necessary TypeScript configuration.
a. Create a new directory for your project and navigate into it:
mkdir MyServerlessApp && cd MyServerlessApp
b. Initialize a new Node.js project:
npm init -y
c. Install TypeScript and the AWS SDK as dependencies:
npm install typescript aws-sdk @types/aws-lambda @types/node --save-dev
d. Initialize a TypeScript configuration file:
npx tsc --init
Adjust the tsconfig.json
to suit the Lambda runtime environment:
{
"compilerOptions": {
"target": "ES2018", // compatible with Node.js 12.x runtime
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
Step 2: Writing Your Lambda Function
Now let’s create a more interesting Lambda function. This function will fetch data from an external JSON placeholder API, process the data, and return a subset of it.
a. Create a src
directory and add a new file handler.ts
:
mkdir src && touch src/handler.ts
b. Add the following TypeScript code to handler.ts
:
import { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda';
import fetch from 'node-fetch';
export async function main(event: APIGatewayEvent, context: Context): Promise<APIGatewayProxyResult> {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const posts = await response.json();
// Return the first 5 posts as an example
return {
statusCode: 200,
body: JSON.stringify(posts.slice(0, 5))
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ message: "Failed to fetch posts", error: error.message })
};
}
}
This function makes an HTTP request to the JSON Placeholder API, retrieves posts, and slices the first 5 posts to return.
c. Compile the TypeScript code:
npx tsc
Step 3: Deploying Your Lambda Function
We need to bundle our Lambda function, including the node-fetch
dependency.
a. Install the node-fetch
package:
npm install node-fetch
b. Use the AWS CLI to create a Lambda function. First, zip your deployment package:
cd dist && zip -r function.zip .
c. Create the Lambda function:
aws lambda create-function --function-name MyServerlessFunction \
--runtime nodejs12.x --role <your-lambda-execution-role-arn> \
--handler handler.main --zip-file fileb://function.zip
Step 4: Setting Up API Gateway
Create an API with a single endpoint to invoke your Lambda function.
a. Navigate to the Amazon API Gateway console and create a new HTTP API.
b. Connect the API route to your Lambda function, using the console’s integration options.
c. Deploy the API and capture the invoke URL.
Test Your Endpoint
Use curl
or Postman to test your API endpoint:
curl https://<your-api-id>.execute-api.<region>.amazonaws.com/default/MyServerlessFunction
You should see the first 5 posts from the JSON Placeholder API.
Conclusion
Congratulations! You’ve just built a more complex serverless application using TypeScript, AWS Lambda, and API Gateway. This example illustrated how you can integrate external services and process data in a serverless environment, enhancing your applications with the power of AWS services. Experiment further by integrating other AWS services or adding
more complex data processing logic. Happy coding in the serverless world!