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
else:
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:
2 thoughts on “80: MS Graph API – Find a user by email (python)”