How to establish connection pooling for HTTP Requests Lambda function attached to AWS API gateway?

17 views Asked by At

I have a lambda function attached to API gateway, So when i send request with one query param it should make a call to one api else other api call, that is handled in lambda function, here I need to have a shared client basically a connection pool, it should not establish different connection for each request. Here when i print the len(pools), it's still 1,How do i achieve shared client connection here?

import json
import urllib3
http = urllib3.PoolManager(num_pools=10)


def lambda_handler(event, context):
 print(event)

 query_param = event.get('queryStringParameters', {}).get('isQuery')

 if query_param == 'true':
    url = 'https://example.com/1'
 else:
    url = 'https://example.com/2'

 headers = {
    'Authorization': 'Bearer token',
    'X-AFB-R-UID': '123456'
   }
 response = http.request('GET', url, headers=headers)

 response_data = {
    'status': response.status,
    'data': response.data.decode('utf-8')  # Assuming it's UTF-8 encoded
   }
 print(response_data, ": Response data")
 print(len(http.pools), ": Number of pools")

 return {
    'statusCode': response.status,
    'body': json.dumps(response_data)  # Convert to JSON before returning
   }
0

There are 0 answers