[PYTHON] [Boto3] Search for Cognito users with the List Users API

The documentation says that you can get the user as follows:

response = client.list_users(
    UserPoolId='string',
    AttributesToGet=[
        'string',
    ],
    Limit=123,
    PaginationToken='string',
    Filter='string'
)

from:https://boto3.readthedocs.io/en/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.list_users

Get 60 users

import boto3
client = boto3.client('cognito-idp')
response = client.list_users(
    UserPoolId='YOUR_USER_POOL_ID'
)

If you specify only the user pool ID, the first 60 all users </ s> will be returned. I thought that "If you do not specify Limit, you will get all the cases", but it seems that only the first 60 cases are acquired.

Search by email address

By writing ʻemail =" hoge "` in Filter, you can search only users with the corresponding email address.

import boto3
client = boto3.client('cognito-idp')
response = client.list_users(
    UserPoolId='YOUR_USER_POOL_ID',
    Filter="email = \"hide\"",
)

In this example, we will get all users who use email addresses that contain the characters hide.

By setting ^ = instead of =, you can also search for "email addresses starting with hide".

Tips: Custom attributes cannot be searched with Filter

You can only search for standard attributes. Custom attributes cannot be searched. This is because only indexed attributes can be searched, and custom attributes cannot be indexed. http://docs.aws.amazon.com/ja_jp/cognito/latest/developerguide/how-to-manage-user-accounts.html#cognito-user-pools-searching-for-users-using-listusers-api

It seems that user search using custom attributes is not currently supported.

It seems better to store the attributes you want to search in DynamoDB or AES (Amazon Elasticsearch Service).

Get the top 10 users

You can narrow down the number of acquisitions by specifying a number in the Limit query.

import boto3
client = boto3.client('cognito-idp')
response = client.list_users(
    UserPoolId='YOUR_USER_POOL_ID',
    Limit=10,
)

Tips: Limit limit is 60

If you try to acquire 61 or more data at once and set Limit to a value of 61 or more, an error will occur.

ClientError: An error occurred (InvalidParameterException) when calling the ListUsers operation: 1 validation error detected: Value '500' at 'limit' failed to satisfy constraint: Member must have value less than or equal to 60

I think it would be better to make a recursive call like the following.

def getUser():
    client = boto3.client('cognito-idp')
    response = self.client.list_users(
        UserPoolId="YOUR_USERPOOL_ID"
    )
    return response

def getUsersWithPagenation(PaginationToken):
    response = self.client.list_users(
        UserPoolId="YOUR_USERPOOL_ID",
        PaginationToken=PaginationToken
    )
    return response

def workerNode(users):
    for user in users["Users"]:
    	# Do Something
    if 'PaginationToken' in users:
        newUsers = getUsersWithPagenation(users["PaginationToken"])
        workerNode(newUsers)

users = getUser()
workerNode(users)

Recommended Posts

[Boto3] Search for Cognito users with the List Users API
Get a list of IAM users with Boto3
Search list for duplicate elements
Call the API with python3.
Specifying the date with the Twitter API
Hit the Etherpad-lite API with Python
Search for homeomorphic idioms with opencv
Python> sys.path> List of strings indicating the path to search for modules
Try sending an email with the Gmail API Client Library for Java
Search for Twitter keywords with tweepy and write the results to Excel
Search for synonyms from the word list (csv) using Python Japanese WordNet
I measured the speed of list comprehension, for and while with python2.7.
[Cloudian # 5] Try to list the objects stored in the bucket with Python (boto3)
Access the Docker Remote API with Requests
Touch around the twitter list with tweepy
Ask for Pi with the bc command
Change the list in a for statement
Search the maze with the python A * algorithm
Heat Map for Grid Search with Matplotlib
The third night of the loop with for
Get holidays with the Google Calendar API
The second night of the loop with for
Play with puns using the COTOHA API
[Reinforcement learning] Search for the best route
Get a list of articles posted by users with Python 3 Qiita API v2
Search for files with line feed code CR + LF under the current directory
Create a clean DB for testing with FastAPI and unittest the API with pytest
After hitting the Qiita API with Python to get a list of articles for beginners, we will visit the god articles
I checked the library for using the Gracenote API
Created a Python wrapper for the Qiita API
Causal reasoning and causal search with Python (for beginners)
Exposing the DCGAN model for Cifar 10 with keras
Until you use the Kaggle API with Colab
Use logger with Python for the time being
I played with Floydhub for the time being
Tips for hitting the ATND API in Python
Get an access token for the Pocket API
Manage AWS nicely with the Python library Boto
Search by the value of the instance in the list
Describe ec2 with boto3 and retrieve the value
Collect images for machine learning (Bing Search API)
Automate background removal for the latest portraits in a directory with Python and API
Build API server for checking the operation of front implementation with python3 and Flask
[For beginners] How to display maps and search boxes using the GoogleMap Javascript API
For Debian users who are having trouble with a bug in the Linux kernel 5.10