GithubHelp home page GithubHelp logo

idanielbot / cdk-http-openapi Goto Github PK

View Code? Open in Web Editor NEW
2.0 1.0 1.0 412 KB

CDK Construct that lets you build AWS Api Gateway Http Api, backed by Lambdas, based on a OpenAPI spec file.

License: MIT License

JavaScript 5.21% TypeScript 94.79%

cdk-http-openapi's Introduction

cdk-http-openapi

CDK Construct that lets you build AWS Api Gateway Http Api, backed by Lambdas, based on a OpenAPI spec file.

Features

  • Deploy Api Gateway Http Api based on a OpenAPI spec file.
  • Each API Route will be backed by 1 NodeJS lambda.
  • Configure CORS for your API.
  • Add custom domain (eg: https://my-awesome-api.my-domain.com) to your API.
  • Enable custom authorizers to Http Api Lambda integrations.
  • Customize your lambdas's memory, timeouts, log retention, env variables and other stuff.

Setup

Add latest package to your project with npm/yarn

npm i --save cdk-http-openapi
yarn add -D cdk-http-openapi

Start using cdk constructs in your infrastructure definition

Examples

1. Define an Http API + 1 lambda for each route

import { HttpOpenApi } from 'cdk-http-openapi'
import { Construct } from 'constructs'
import { Stack } from 'aws-cdk-lib'

export class MyServiceStack extends Stack {
  constructor(
    scope: Construct,
    id: string,
  ) {
    super(scope, id)
    // other resources for your microservice

    // define your API + lambdas
    const api = new HttpOpenApi(this, 'MyApi', {
      functionNamePrefix: 'cool-api',
      openApiSpec: './openapi.yml',
      lambdasSourcePath: './dist/src', // optional. It defaults to './.build/src'
      integrations: [
        {
          operationId: 'getEntity', // for each operation you define in your OpenAPI spec
          handler: 'api.getEntity', // you can register a lambda handler to handle your http request
        },
        {
          operationId: 'storeEntity',
          handler: 'api.storeEntity',
          timeoutSeconds: 5,        // timeout configuration for lambda
          memorySize: 512,          // memory configuration for lambda
          env: {                    // you can also inject ENV variables into your lambda
            DB_HOST: '...',
            DB_USERNAME: '...',
            DB_PASSWORD: '...'
          },
        }
      ]
    });

  }
}

2. Enable Custom Domain for your API: my-awesome-api.cool.io

const api = new HttpOpenApi(this, 'MyApi', {
    ...
})

const domainName = 'my-awesome-api.cool.io';
const certificateArn = `arn:aws:acm:${AWS_REGION}:${AWS_ACCOUNT}:certificate/${CERTIFICATE_ID}`;
const hostedZone = 'cool.io';

api.enableCustomDomain(domainName, certificateArn, hostedZone);

3. Configure wildcard CORS (allow '*')

const api = new HttpOpenApi(this, 'MyApi', {
    functionNamePrefix: 'my-service',
    openApiSpec: './openapi.yml',

    // ... other props

    corsAllowAllOrigins: true,
    
});

4. Configure CORS more specific

const api = new HttpOpenApi(this, 'MyApi', {
    functionNamePrefix: 'my-service',
    openApiSpec: './openapi.yml',

    // ... other props

    // See AWS Docs for more info: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html
    corsConfig: {
        allowMethods: ['GET', 'POST'],
        allowHeaders: ['application/json', 'authorization'],
        allowOrigins: ['https://my-frontend.com']
    }
});

5. Enable Customer Authorizer Lambda for your endpoints

const api = new HttpOpenApi(this, 'MyApi', {
    functionNamePrefix: 'my-service',
    openApiSpec: './openapi.yml',

    // ... other props
    
    customAuthorizerLambdaArn: `arn:aws:lambda:${AWS_REGION}:${AWS_ACCOUNT}:function:${AUTHORIZER_LAMBDA_NAME}`
   
});

cdk-http-openapi's People

Contributors

idanielbot avatar

Stargazers

 avatar Josua Blejeru  avatar

Watchers

 avatar

Forkers

josuablejeru

cdk-http-openapi's Issues

Adding support for separation of the lambda codebase

Currently, all code that is landing in the build directory is uploaded to each lambda with all dependencies and files. It would be super cool if we could optionally separate each source code file to its specific lambda function. Shared code could be added to each lambda by using a common base layer which is attached to each lambda.

the directory structure could be looking like this:

lambda/
├─ common/
│  ├─ client.ts
│  ├─ utils.ts
├─ function-a/
│  ├─ handler.ts
│  ├─ package.json
│  ├─ package-lock.json
│  ├─ node_modules/
│  ├─ calculate.ts
├─ function-b/
│  ├─ handler.ts
│  ├─ package.json
│  ├─ package-lock.json
│  ├─ node_modules/
│  ├─ external.ts

Code example doesn't work

I copied the code example from the repo, and it doesn't work for me.

First of all there's a typo, there's a comma missing at the end of the line with lambdasSourcePath.

After fixing that, I get the error:

Argument of type '{ serviceName: string; openApiSpec: string; lambdasSourcePath: string; integrations: ({ operationId: string; handler: string; } | { operationId: string; handler: string; timeoutSeconds: number; memorySize: number; env: { ...; }; })[]; }' is not assignable to parameter of type 'HttpApiProps'.
Object literal may only specify known properties, and 'serviceName' does not exist in type 'HttpApiProps'.ts(2345)

Node version: 16.18.1
cdk version: 2.50.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.