80: MS Graph API – Find a user by email (python)

A simple method for finding a user by email via Graph API

def GetUserByEmail(email):
    headers = {"AUTHORIZATION": f"Bearer {token}", "Content-type": "application/json"}
    url = f"https://graph.microsoft.com/v1.0/users?$filter=mail eq '{email}'"
    response = requests.get(url=url, headers=headers)
    if response.status_code == 200 :
        item = response.json()
        if len(item["value"]) != 0 :
            _user = response.json()["value"][0]
            return _user
            logger.error(f"ERROR: User {email} not found: {response.status_code}")
        return None
    else :
        logger.error(f"Error: User {email} is borked: {response.json()}")
        return None

In this code fragment, we hit the user API with a filter for the user’s email address.

The endpoint always returns an object regardless, so we need to check for the length of the Value array.

If this is empty we return a null value.

You may also like:

66: Python: MS Graph API Authentication (Without a user)

81: MS Graph API – Remove a User from a Group (Python)

2 thoughts on “80: MS Graph API – Find a user by email (python)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s