1
votes

I am trying to create a basic example of using API Gateway WebSocket connecting to an AWS Lambda function.

I followed the example from this link.

The goal is to have one Lambda csproj with multiple entry-points (functions), same as specified in the example above.

API Gateway:

I have four routes, all of them connecting to the same lambda function: cgavan-websocket-2:

  • $connect
  • $disconnect
  • echo
  • $default

Lambda function:

I have a lambda project with four different functions:

  • Connect.FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)

  • Disconnect.FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)

  • Echo.FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)

  • Default.FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)

Question:

How can I specify, for each of the API Gateway routes, which function handler to invoke from the Lambda csproj?

Right now, when I connect to the API Gateway WebSocket (with the WebSocket Request Route: $connect), it always invokes the Default.FunctionHandler().

API Gateway route

enter image description here

1
Do you have four lambda functions or trying to implement it from same lambda? - Sridhar Raju
@SridharRaju I am trying to implement it from the same lambda function. - Catalin
Then you have handle the routes from your function. using the information we get in event which has eventType. I have implemented the same type in python if you want I will post it below. - Sridhar Raju
Yes, please. That would be very helpful. - Catalin

1 Answers

1
votes

This is similar kind of implementation for websocket-api, which sends a random message on being triggered. Here event_type MESSAGE is a custom one according to your needs.

import time
import json
import boto3


def lambda_handler(event, context):
    print(event)
    event_type = event["requestContext"]["eventType"]

    if event_type == "CONNECT" or event_type == "DISCONNECT":
        response = {'statusCode': 200}
        return response     
    
    elif event_type == "MESSAGE":   
        connection_id = event["requestContext"]["connectionId"]
        domain_name = event["requestContext"]["domainName"]
        stage = event["requestContext"]["stage"]

        message = f'{domain_name}: {connection_id}'.encode('utf-8')
        api_client = boto3.client('apigatewaymanagementapi', endpoint_url = f"https://{domain_name}/{stage}")

        for _ in range(5):
            api_client.post_to_connection(Data=message,
                                                ConnectionId=connection_id)
            time.sleep(5)

    
        response = {'statusCode': 200}
        return response