Reputation: 461
in order to list all users of a cognito user-pool, I thought of using boto3's client.list_users()
-function including pagination.
However, if I call print(client.can_paginate('list_users'))
, False
is returned since this function list_users()
is not pageable.
Is there an alternative to listing all users of a cognito user-pool without filtering those users out that have already been selected?
My current code without pagination looks this:
client = boto3.client('cognito-idp',
region_name=aws_region,
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
config=config)
response = client.list_users(
UserPoolId=userpool_id,
AttributesToGet=[
'email','sub'
]
)
Many thanks in advance!
Upvotes: 3
Views: 5048
Reputation: 3212
This worked for me, it seems there is a Paginator for list_user in boto3 cognito idp documentation:
def get_cognito_users(**kwargs) -> [dict]:
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html?highlight=list_users#CognitoIdentityProvider.Paginator.ListUsers
paginator = cognito_idp_client.get_paginator('list_users')
pages = paginator.paginate(**kwargs)
for page in pages:
users = []
for obj in page.get('Users', []):
users.append(obj)
yield users
Upvotes: 2
Reputation: 761
Faced with the same problem, was also surprised that there is no paginator for the Cognito list_user API, so I've built something like this:
import boto3
def boto3_paginate(method_to_paginate, **params_to_pass):
response = method_to_paginate(**params_to_pass)
yield response
while response.get('PaginationToken', None):
response = method_to_paginate(PaginationToken=response['PaginationToken'], **params_to_pass)
yield response
class CognitoIDPClient:
def __init__(self):
self.client = boto3.client('cognito-idp', region_name=settings.COGNITO_AWS_REGION)
...
def get_all_users(self):
"""
Fetch all users from cognito
"""
# sadly, but there is no paginator for 'list_users' which is ... weird
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cognito-idp.html?highlight=list_users#paginators
users = []
# if `Limit` is not provided - the api will return 60 items, which is maximum
for page in boto3_paginate(self.client.list_users, UserPoolId=settings.COGNITO_USER_POOL):
users += page['Users']
return users
Upvotes: 5