CodeWithYou

AWS Lambda proxy integrations for HTTP APIs in AWS CDK

Published on
Authors
AWS Lambda proxy integrations for HTTP APIs in AWS CDK

Photo by Jack Barton

A Lambda proxy integration enables you to integrate an API route with a Lambda function. When a client calls your API, API Gateway sends the request to the Lambda function and returns the function's response to the client. Today, I will show you how to create a Lambda proxy integration for an HTTP API in AWS CDK.

Let see my snippet of code:

const api = new HttpApi(this, 'HttpApi', {
  description: 'sample http api',
  corsPreflight: {
    allowHeaders: ['Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key'],
    allowMethods: [
      CorsHttpMethod.OPTIONS,
      CorsHttpMethod.GET,
      CorsHttpMethod.POST,
      CorsHttpMethod.PUT,
      CorsHttpMethod.PATCH,
      CorsHttpMethod.DELETE,
    ],
    allowCredentials: true,
    allowOrigins: ['http://localhost:8080'],
  },
})

// lambda function
const fn = new NodejsFunction(this, 'SampleFunction', {
  entry: './lambda/index.ts',
  runtime: lambda.Runtime.NODEJS_14_X,
  handler: 'main',
  architecture: lambda.Architecture.ARM_64,
  logRetention: logs.RetentionDays.ONE_WEEK,
  bundling: {
    externalModules: ['aws-sdk'],
    minify: true,
  },
})

// add route with lambda integration
api.addRoutes({
  path: '/api',
  methods: [HttpMethod.GET],
  integration: new apiGatewayIntegrations.HttpLambdaIntegration('fn-integration', fn, {}),
})

Let's go over what we did in the code above:

  1. We created a HttpApi by instantiating the HttpApi class. We allow the user to specify CORS preflight settings.
  2. We created a NodejsFunction by instantiating the NodejsFunction class. We allow the user to specify the entry point, runtime, handler, architecture, and log retention.
  3. We created a HttpLambdaIntegration by instantiating the HttpLambdaIntegration class. We allow the user to specify the integration type, function, and options.

This code of article is available on GitHub

Let see the code of lambda function. This function use typescript to write the code. You can see how to build Lambda functions with TypeScript in AWS CDK

import { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from 'aws-lambda'

export async function main(event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> {
  return {
    body: JSON.stringify(event),
    statusCode: 200,
    isBase64Encoded: false,
    headers: {
      'Content-Type': 'application/json',
    },
  }
}

This function is very simple. It just return the event object.

Now deploy whole stack.

yarn deploy
Advertisement

After deploy successfully, you can see the an api url in the console. Open the url and you will see the event object.

{
  "version": "2.0",
  "routeKey": "GET /api",
  "rawPath": "/api",
  "rawQueryString": "",
  "headers": {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "en-GB,en-US;q=0.9,en;q=0.8,vi;q=0.7,bs;q=0.6",
    "content-length": "0",
    "host": "6ydlgx7176.execute-api.ap-southeast-1.amazonaws.com",
    "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\", \"Google Chrome\";v=\"102\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"macOS\"",
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "none",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36",
    "x-amzn-trace-id": "Root=1-62b4282c-37fc9cd35cb31bb372c82645",
    "x-forwarded-for": "118.69.55.211",
    "x-forwarded-port": "443",
    "x-forwarded-proto": "https"
  },
  "requestContext": {
    "accountId": "820710015775",
    "apiId": "6ydlgx7176",
    "domainName": "6ydlgx7176.execute-api.ap-southeast-1.amazonaws.com",
    "domainPrefix": "6ydlgx7176",
    "http": {
      "method": "GET",
      "path": "/api",
      "protocol": "HTTP/1.1",
      "sourceIp": "118.69.55.211",
      "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
    },
    "requestId": "UKs3ChwzSQ0EJYA=",
    "routeKey": "GET /api",
    "stage": "$default",
    "time": "23/Jun/2022:08:45:32 +0000",
    "timeEpoch": 1655973932896
  },
  "isBase64Encoded": false
}

That all, it is very simple, right :). Thanks for reading this article. If you have any questions, please free leave a comment. I will try to answer you as soon as possible. Thank you!

Ah, I forgot to mention that you should run below command to clean the stack.

npx cdk destroy
Advertisement