So if you have read through my previous articles (here, and here) discussing AWS Web Socket API Gateways and how to configure them you will see an evolution of complexity. Today I hope to show you a new way to do this that takes ALL of the frustration and complexity out of building an event driven web socket api with AWS API Gateway.
Check out aws-websocket-sam-helper. Instead of building out a template.yaml file that is thousands of lines long you can simply describe your lambda function with a simple json file and the rest will be done for you.
The project I referenced above ws-sam-helper-example shows you how to use the SAM Helper.
Here is an example of documenting a Lambda function that will handle a Web Socket route with the key get-user.
{
"functionName": "GetUserFunction",
"routeKey": "get-user",
"apiId": "ApiBuiltBySamHelper",
"handler": "user/index.getHandler",
"policies": ["AmazonAPIGatewayInvokeFullAccess", "AmazonAPIGatewayAdministrator"]
}That little JSON snippet builds out all of the following yaml for you:
# Route
#===========================
# Key: get-user route handler
# Handler: GetUserFunction
#===========================
GetUserFunctionRoute:
Type: AWS::ApiGatewayV2::Route
Properties:
ApiId: !Ref ApiBuiltBySamHelper
RouteKey: get-user
AuthorizationType: NONE
OperationName: GetUserFunctionRoute
Target: !Join
- '/'
- - 'integrations'
- !Ref GetUserFunctionInteg
GetUserFunctionInteg:
Type: AWS::ApiGatewayV2::Integration
Properties:
ApiId: !Ref ApiBuiltBySamHelper
Description: GetUserFunction Integration
IntegrationType: AWS_PROXY
IntegrationUri:
Fn::Sub:
arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${ GetUserFunction.Arn }/invocations
GetUserFunctionPermission:
Type: AWS::Lambda::Permission
DependsOn:
- ApiBuiltBySamHelper
- GetUserFunction
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref GetUserFunction
Principal: apigateway.amazonaws.com
GetUserFunction:
Type: AWS::Serverless::Function
Properties:
Handler: user/index.getHandler
Timeout: 30
Runtime: nodejs8.10
CodeUri: ./
Policies:
- AmazonAPIGatewayInvokeFullAccess
- AmazonAPIGatewayAdministratorOther than creating a function.json file for your functions you simply have to describe your api in your package.json file like below. That coupled with the function definitions will build out a complete SAM Template for you that can be used to deploy your web socket API Gateway API and lambdas.
"api": [
{
"apiId": "ApiBuiltBySamHelper",
"apiName": "my-api-from-sam",
"stageName": "v1",
"stageDescription": "Version 1 of the api.",
"routeSelectionExpression": "$request.body.action",
"type": "websocket"
}
]Just run the sam-helper command in your project and it will discover all of your functions and build out your template.yaml file for you.
The tool is new and simple. I am hoping to find the time to add more features and support the REST Api Gateway as well.