2
votes

I am using WebSocket ApiGateway with AWS Lambda integration. When I try to post data to a client with post_to_connection method of boto3.client('apigatewaymanagementapi') the Lambda function always times out without any error message. Only the timeout message gets logged in CloudWatch:

Task timed out after 3.00 seconds

My code:

import json
import boto3
import time
import urllib

api_client = boto3.client('apigatewaymanagementapi')

def lambda_handler(event, context):

    connectionId = event['requestContext']['connectionId']

    api_client.post_to_connection(ConnectionId=connectionId, Data=json.dumps({'test': '1'}))

    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
        }

What am I doing wrong?

1

1 Answers

7
votes

I found [this post][1] asking for a clearer boto3 documentation. It turns out that if you instantiate apigatewaymanagementapi client you must pass endpoint_url argument, but the function will not throw any errors if you won't. Anyway, the api_client should be created like this:

api_client = boto3.client('apigatewaymanagementapi',
endpoint_url='https://{api-id}.execute-api.{your-aws-region}.amazonaws.com/{stage}')

Caution: do not pass a url string with '@connections' at the end to endpoint_url [1]: https://github.com/boto/boto3/issues/1914