Skip to content
Go back

Deploying a Serverless API with AWS Lambda + API Gateway

Deploying a Serverless API with AWS Lambda + API Gateway

Introduction

Serverless APIs reduce operational overhead by running code on-demand. This guide covers creating AWS Lambda functions, configuring API Gateway, and deploying via AWS CDK.

Prerequisites

Step 1: Initialize CDK Project

mkdir serverless-api
cd serverless-api
cdk init app --language typescript

Step 2: Install Dependencies

npm install @aws-cdk/aws-lambda @aws-cdk/aws-apigateway

Step 3: Create Lambda Function

In lambda/handler.js:

exports.handler = async (event) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({ message: 'Hello from Lambda!' }),
  };
  return response;
};

Step 4: Define CDK Stack

Edit lib/serverless_api-stack.ts:

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as apigw from 'aws-cdk-lib/aws-apigateway';

export class ServerlessApiStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Lambda function
    const apiLambda = new lambda.Function(this, 'ApiHandler', {
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: 'handler.handler',
      code: lambda.Code.fromAsset('lambda'),
    });

    // API Gateway REST API
    const api = new apigw.LambdaRestApi(this, 'ServerlessApi', {
      handler: apiLambda,
      restApiName: 'Serverless Service',
      proxy: false,
    });

    // Define /hello resource
    const hello = api.root.addResource('hello');
    hello.addMethod('GET'); // GET /hello
  }
}

Step 5: Deploy Stack

cdk deploy

Note the API endpoint URL output.

Step 6: Test the API

curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/hello

Returns:

{ "message": "Hello from Lambda!" }

Step 7: Environment Variables

Add environment variables to Lambda:

const apiLambda = new lambda.Function(this, 'ApiHandler', {
  runtime: lambda.Runtime.NODEJS_18_X,
  handler: 'handler.handler',
  code: lambda.Code.fromAsset('lambda'),
  environment: {
    STAGE: this.node.tryGetContext('stage') || 'dev',
  },
});

Step 8: CI/CD with GitHub Actions

Use CDK GitHub Actions:

name: Deploy Serverless API
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: aws-actions/configure-aws-credentials@v2
        with:
          aws-region: us-east-1
          role-to-assume: arn:aws:iam::123456789012:role/CDKDeployRole
      - uses: aws-actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm ci
      - run: npm run build
      - run: npx cdk deploy --require-approval never

Summary

AWS Lambda & API Gateway with AWS CDK provide a scalable, cost-effective serverless API solution. Leverage IaC and CI/CD for automated, repeatable deployments.


Share this post on:

Previous Post
Implementing DALL-E Image Generation in React
Next Post
Using Whisper for Speech-to-Text in Web Apps