Package: crow-api.core
Crow APICrow API lets you build an API intuitively based on the file structure of a project. Provide API Gateway and Lambda function configurations and crow will build out the appropriate paths and methods to the API Gateway. All created resources are available after initialization.lambdaFunctionswill expose all Lambda functions created for further operations like adding environment variables and providing permissions.crow-apiversionaws-cdkversionNotes0112Not recommended for use22Contents:Getting StartedExample File StructureCrow API PropssourceDirectorysharedDirectoryuseAuthorizerLambdaauthorizerDirectoryauthorizerLambdaConfigurationtokenAuthorizerConfigurationcreateApiKeylogRetentionapiGatewayNameapiGatewayConfigurationlambdaConfigurationslambdaIntegrationOptionsmodelsrequestValidatorsmethodConfigurationsPropertiesgatewayauthorizerauthorizerLambdalambdaLayerlambdaFunctionsmodelsrequestValidatorsGetting StartedStart your application as a normal CDK appnpminstall-gaws-cdk
cdkbootstrap# If this is your first cdk app, you will need to bootstrap your AWS accountcdkinitapp--languagetypescriptNext, install the Crow API packagenpminstall--savecrow-apiIn thelib/folder generated by thecdk, there should be a single file named<your-app>-stack.js. Create your Crow API construct inside of that file like so# Example automatically generated from non-compiling source. May contain errors.fromaws_cdkimportStack,StackPropsfromconstructsimportConstructfromcrow_apiimportCrowApi,ICrowApiPropsclassYourAppStack(Stack):def__init__(self,scope,id,props):super().__init__(scope,id,props){crowApiProps,}=propsapi=CrowApi(self,"api",{(SpreadAssignment...crowApiPropscrow_api_props)})Your API will start to take shape as you create folders to define paths and methods (see Example File Structure below). To deploy your API, simply runcdk synthandcdk deploy. Follow the instructions as they are prompted, and you will end up receiving a URL where your API now lives.Example File Structure|-- src/
    |-- authorizer/
        |-- index.js
    |-- v1/
        |-- book/
            |-- get/
                |-- index.js
            |-- post/
                |-- index.js
        |-- chapters/
            |-- get/
                |-- index.js
        |-- authors/
            |-- get/
                |-- index.js
            |-- post/
                |-- index.jsThe preceding file structure will create an API with the following routes:GET /v1/bookPOST /v1/bookGET /v1/book/chaptersGET /v1/authorsPOST /v1/authorsThere needs to be anindex.jsfile inside of a folder named after an HTTP method in order for a path to be created. Theindex.jsfile needs to export ahandlermethod that will process the payload and return like the following.exports.handler=asyncfunction(event,context,callback){try{constdata={statusCode:201,};returndata;}catch(uncaughtError){console.error(uncaughtError);throwuncaughtError;}}Crow API PropsCrow API takes in a few props to help you customize away from defaults.sourceDirectoryBy default, Crow walks through thesrcdirectory in the root of the repository to determine routes and methods, but you can change the top level directory by passing in thesourceDirectoryprop. The string passed in should not start with or end with a slash (/). For example,src,api/src, orsourceare all valid options to pass in through that prop.sharedDirectoryBy default, Crow creates a Lambda layer out of theshareddirectory in the source directory of the repository, but you can change the name of the shared directory by passing in thesharedDirectoryprop. The string passed in should not start with or end with a slash (/) and must be a direct child of the source directory. For example,commonorutilsare valid butshared/utilsis not.The Lambda layer created will be prepended to any the of the layers passed in throughlambdaConfigurationsand added to all Lambda functions created.useAuthorizerLambdaCrow will create and attach an authorizer Lambda to specific methods if requested. TheuseAuthorizerLambdaprop tells theCrowApiConstruct that it should create an authorizer Lambda and accepts a boolean value. This isfalseby default.authorizerDirectoryCrow will allow for a Lambda authorizer to be created and used by specific methods if requested. TheauthorizerDirectoryprop tells Crow where to find the code for the Lambda authorizerwithin the source directory which can be specified in thesourceDirectoryprop. It expects to find anindex.jsfile that exports ahandlerfunction within theauthorizerDirectory.By default, Crow expects to find a directory calledsrc/authorizercontaining the authorizer Lambda source if theuseAuthorizerLambdaprop istrue. If a different directory within the source directory should be looked at for this code, it should be specified by passing in a string to theauthorizerDirectoryprop. The string passed in should not start with nor end with a slash (/). For example,authorauthLambdaSrcare valid.authorizerLambdaConfigurationTheauthorizerLambdaConfigurationprop is passed directly to the Lambda functions which will be in charge of your API's authorization. The configuration allowed is exactly the same as theLambda Function props.tokenAuthorizerConfigurationThetokenAuthorizerConfigurationprop is passed directly to theAPIGateway.TokenAuthorizerconstruct which will be in charge of your API's authorization. Anything available in theclass constructor for theTokenAuthorizercan be overridden.Note:Be careful with this configuration item as all configuration here takes precedence over Crow defaults. I suggest not using this configuration item unless you are experienced with the AWS CDK, API Gateway, and Lambda.createApiKeyBy default, Crow does not create an API key associated with the API. If an API key is desired, pass in thecreateApiKeyprop astrue.logRetentionBy default, Crow creates log groups for resources it creates and sets the log retention to one week. If a different retention is desired pass in thelogRetentionprop ofenum typeRetentionDays.apiGatewayConfigurationThis props allows for more complex overrides to the API Gateway that fronts your API. The configuration allowed is exactly the same as theRestApi props.Note:Be careful with this configuration item as all configuration here takes precedence over Crow defaults. I suggest not using this configuration item unless you are experienced with the AWS CDK and API Gateway.An example of this prop might look like the following:# Example automatically generated from non-compiling source. May contain errors.fromsource_map_support.registerimportimportaws_cdkascdkimportaws_cdk.aws_apigatewayasapigatewayfrom...lib.crow_api_stackimportCrowApiStackdev_environment={"account":"123456789012","region":"us-east-1"}app=cdk.App()CrowApiStack(app,"CrowApiStack",env=dev_environment,api_gateway_configuration={"endpoint_configuration":{"types":[apigateway.EndpointType.REGIONAL]}})apiGatewayNameThis is a simple prop that names the API Gateway. This is how the API will be identified in the AWS console. The value should be a string without spaces and defaults tocrow-api.lambdaConfigurationsThis props allows for more complex overrides to Lambda functions. The prop is an object with keys corresponding to the API path of a Lambda function and a value corresponding to the configuration that should be applied to the Lambda. The configuration allowed is exactly the same as theLambda Function props.Note:Be careful with this configuration item as all configuration here takes precedence over Crow defaults. I suggest not using this configuration item unless you are experienced with the AWS CDK and Lambda.An example of this prop might look like the following:# Example automatically generated from non-compiling source. May contain errors.fromsource_map_support.registerimportimportaws_cdkascdkfrom...lib.crow_api_stackimportCrowApiStackdev_environment={"account":"123456789012","region":"us-east-1"}app=cdk.App()CrowApiStack(app,"CrowApiStack",env=dev_environment,lambda_configurations={"/v1/book/get":{"timeout":cdk.Duration.seconds(5)}})lambdaIntegrationOptionsThis prop is an object with keys corresponding to the API path of a Lambda function and a value corresponding to the configuration that should be applied to the Lambda Integration. The configuration allowed is exactly the same as theLambdaIntegrationOptions.modelsThis prop helps set up theModels used inmethodConfigurationabove. It is an array ofCrowModelOptionswhich are the same asMethodOptionsexcept that themodelNameis required. TheModels will receive an ID equal to itsmodelNamewhich is why that prop is required. TheIModelcan then be referenced inmethodConfigurationsusing itsmodelName.requestValidatorsThis prop helps set up theRequestValidators used inmethodConfigurationabove. It is an array ofCrowRequestValidatorOptionswhich are the same asRequestValidatorOptionsexcept that therequestValidatorNameis required. TheRequestValidators will receive an ID equal to itsrequestValidatorNamewhich is why that prop is required. TheIRequestValidatorcan then be referenced inmethodConfigurationsusing itsrequestValidatorName.methodConfigurationsThis prop allows for more complex overrides to individual methods. The prop is an object with keys corresponding to the API path of a method and a value corresponding to the configuration that should be applied to the method as well as the keyuseAuthorizerLambdawhich will invoke the authorizer Lambda whenever the method is called. The configuration allowed is almost exactly the same asMethodOptionsplus theuseAuthorizerLambdaboolean.The differences betweenMethodOptionsand Crow'sCrowMethodConfiguration(the type for this prop) is that any value referencing{ [string]: IModel }(MethodOptions.requestModelsandMethodResponse.responseModels) has been changed to{ [string]: string }and similarlyrequestValidatorhas been changed fromIRequestValidatortostring. The strings that are passed should correspond with themodelNames orrequestValidatorNames used in themodelsandrequestValidatorsprops (see next sections).Note:IfcreateApiKeyistrue, then theapiKeyRequiredparameter will need to be set for the methods needing the API key.An example of this prop might look like the following:# Example automatically generated from non-compiling source. May contain errors.fromsource_map_support.registerimportimportaws_cdkascdkfrom...lib.crow_api_stackimportCrowApiStackdev_environment={"account":"123456789012","region":"us-east-1"}app=cdk.App()CrowApiStack(app,"CrowApiStack",env=dev_environment,models=[{"model_name":"authorsPost","schema":{"schema":apigateway.JsonSchemaVersion.DRAFT4,"title":"/v1/authors/post","type":apigateway.JsonSchemaType.OBJECT,"required":["name"],"properties":{"name":{"type":apigateway.JsonSchemaType.STRING}}}}],method_configurations={"/v1/authors/post":{"api_key_required":True,"request_models":{"application/json":"authorsPost"}},"/v1/book/get":{"use_authorizer_lambda":True},"/v1/book/post":{"api_key_required":True}})PropertiesACrowApiconstruct will give full access to all of the resources it created.gatewayThis is theapigateway.RestApithat all of the created Lambda functions sit behind.usagePlanThis is theapigateway.UsagePlanassociated with the API Gateway and pre-created API key if that is enabled.authorizerThis is theapigateway.IAuthorizerthat is attached to the API Gateway.authorizerLambdaThis is thelambda.Functionthat authorizes API Gateway requests.lambdaLayerIf thesharedDirectoryis populated, this is thelambda.LayerVersioncreated for that code. If thesharedDirectoryis not populated, then this isundefined.lambdaFunctionsThis is an object with keys being the API paths and the values being thelambda.Functions sitting being them. Continuing off of the example file structure from above, the following would be an example of referencingGET/v1/book/chapters.# Example automatically generated from non-compiling source. May contain errors.fromaws_cdkimportStack,StackPropsfromconstructsimportConstructfromcrow_apiimportCrowApi,ICrowApiPropsclassYourAppStack(Stack):def__init__(self,scope,id,props):super().__init__(scope,id,props){crowApiProps,}=propsapi=CrowApi(self,"api",{(SpreadAssignment...crowApiPropscrow_api_props)})lambda_=api.lambda_functions["/v1/book/chapters/get"]lambda_.add_environment("FOO","bar")modelsThis is an object with keys being themodelNames and values being theIModels created.requestValidatorsThis is an object with keys being therequestValidatorNames and values being theIRequestValidators created.