Following on from yesterday’s post on Finding a user by email, here’s a method for removing a user from an AAD group using MS Graph API.
def RemoveUserFromGroup(user, group_id):
headers = {"AUTHORIZATION": f"Bearer {token}", "Content-type": "application/json"}
url = f"https://graph.microsoft.com/v1.0/groups/{group_id}/members/{user['id']}/$ref"
response = requests.delete(url=url, headers=headers, json=data)
if response.status_code == 204 :
logger.info(f"User {user['displayName']} removed to group: {response.status_code}")
elif response.status_code == 200 :
logger.error(f"ERROR: User {user['displayName']} does not exist in the group: {response.status_code}")
else:
logger.error(f"ERROR: User {user['displayName']} cannot be removed: {response.status_code}")
I’m passing in the full user object received from the GetUserByEmail method.
We use the User’s Id property in the /groups/ endpoint to remove the user from the Group ID.
If the user is removed, the endpoint will return a status code of 204.
If the user isn’t in the group and can’t be removed, the endpoint will return a status code of 200.
2 thoughts on “81: MS Graph API – Remove a User from a Group (Python)”