AWS CDK
API Gateway
Lambda
OpenAPI
Cloud Development Kit

AWS CDK how to create an API Gateway backed by Lambda from OpenApi spec?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating an API Gateway backed by Lambda from an OpenAPI spec in AWS CDK is a common infrastructure-as-code workflow. The key is wiring the OpenAPI definition to the API construct and attaching Lambda integrations in a repeatable deployment pipeline. A good setup keeps spec ownership clear and minimizes drift between code and API contract.

Core Sections

Choose the Right API Gateway Type

In CDK you can use REST API or HTTP API constructs. OpenAPI import support is strongest with REST API for many advanced features, while HTTP API is lighter and cheaper for simpler use cases.

Define Lambda Backend in CDK

Start by creating Lambda functions with explicit runtime, handler, and code path.

typescript
1import * as cdk from 'aws-cdk-lib';
2import * as lambda from 'aws-cdk-lib/aws-lambda';
3import { Construct } from 'constructs';
4
5export class ApiStack extends cdk.Stack {
6  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
7    super(scope, id, props);
8
9    const handler = new lambda.Function(this, 'HelloFn', {
10      runtime: lambda.Runtime.NODEJS_20_X,
11      handler: 'index.handler',
12      code: lambda.Code.fromAsset('lambda/hello'),
13    });
14  }
15}

Keep function names stable for easier integration mapping.

Import OpenAPI Spec with Integration Extensions

For REST API import, include API Gateway extension fields in spec, such as x-amazon-apigateway-integration.

yaml
1paths:
2  /hello:
3    get:
4      responses:
5        "200":
6          description: ok
7      x-amazon-apigateway-integration:
8        type: aws_proxy
9        httpMethod: POST
10        uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${HelloFnArn}/invocations

Placeholders can be replaced during synthesis or deployment.

Create API from Spec in CDK

Use SpecRestApi with ApiDefinition.fromAsset.

typescript
1import * as apigateway from 'aws-cdk-lib/aws-apigateway';
2
3const api = new apigateway.SpecRestApi(this, 'OpenApiRest', {
4  apiDefinition: apigateway.ApiDefinition.fromAsset('openapi/api.yaml'),
5  deploy: true,
6  restApiName: 'openapi-lambda-api',
7});

If your spec references Lambda ARNs, automate substitution to avoid manual edits.

Grant Invoke Permissions

API Gateway must be allowed to invoke Lambda. Add explicit permissions for the execute API ARN.

typescript
1handler.addPermission('ApiInvokePermission', {
2  principal: new cdk.aws_iam.ServicePrincipal('apigateway.amazonaws.com'),
3  sourceArn: api.arnForExecuteApi('*', '/*', '*'),
4});

Missing permission is a frequent cause of runtime integration errors.

Manage Spec and Infrastructure Drift

Store OpenAPI spec in source control beside CDK stack. Add validation in CI to ensure spec is syntactically valid and deployment substitutions are applied consistently. Drift between runtime integration URIs and spec contract creates hard-to-debug production issues.

Deployment and Stage Strategy

Use separate stages for dev, test, and production. Keep environment-specific variables in CDK context or parameter stores, not in duplicated specs. This keeps one contract with controlled deployment differences.

Production Workflow with Spec Validation

Treat OpenAPI as a first-class artifact in CI. Validate schema syntax before CDK synth and fail early when contracts are invalid.

bash
npm run lint
npx cdk synth

Add a contract test step that deploys to a temporary stage and runs smoke requests against key endpoints. This catches integration placeholder mistakes and permission errors before production rollout.

Environment-aware Substitution Strategy

For multi-environment deployments, avoid hardcoded account and region values in raw specs. Keep placeholders and inject values from CDK context or pipeline variables. This keeps one reusable contract and reduces copy errors.

typescript
const helloFnArn = handler.functionArn;
new cdk.CfnOutput(this, 'HelloFnArn', { value: helloFnArn });

When teams manage many APIs, create a shared construct for spec loading, substitution, and permission grants. Standardization reduces deployment drift and review overhead.

Documenting substitution rules and deployment assumptions in repository docs helps reduce onboarding errors and prevents accidental contract drift during urgent releases.

Common Pitfalls

  • Mixing REST and HTTP API assumptions while importing OpenAPI definitions.
  • Hardcoding Lambda ARNs directly in specs across multiple environments.
  • Forgetting Lambda invoke permissions for API Gateway.
  • Allowing spec and CDK code to diverge without CI checks.
  • Deploying stage-specific behavior through manual console edits.

Summary

  • Use CDK SpecRestApi to import OpenAPI-driven REST APIs.
  • Define Lambda backends in code and integrate through spec extensions.
  • Grant explicit invoke permissions to avoid runtime failures.
  • Keep spec and infrastructure in one versioned workflow.
  • Use staged deployments and automation to prevent contract drift.

Course illustration
Course illustration

All Rights Reserved.