82: MS Graph API – Adding Users to a group (python)

Following up on my posts on:

Here is another simple script for adding users to an Azure Active Directory (AAD) Group.

def AddUserToGroup(user, group_id):
    """ 
        Adds a user to an AAD group 
        User = User object from GetUserByEmail()
        group_id = AAD group id
    """
    headers = {"AUTHORIZATION": f"Bearer {token}", "Content-type": "application/json"}
    url = f"https://graph.microsoft.com/v1.0/groups/{group_id}/members/$ref"
    data = {
        "@odata.id": f"https://graph.microsoft.com/v1.0/directoryObjects/{user['id']}"
        }
    response = requests.post(url=url, headers=headers, json=data)
    
    if response.status_code == 204 :
        logger.info(f"User {user['displayName']} added to group: {response.status_code}")
    elif response.status_code == 400 :
        logger.error(f"ERROR: User {user['displayName']} already exist in the group: {response.status_code}")
    elif response.status_code == 404 :
        logger.error(f"ERROR: User {user['displayName']} or group not found: {response.status_code}")

I’m passing the user object received from the GetUserByEmail method, previously shared and the AAD Group ID defined in an environment variable.

Return codes

204 – The Users has been successfully added to the group
400 – The Users already exists in the group
404 – The user or group cannot be found.

This method adds asignle user, but the endpoint supports batch uploading via a PATCH Request

PATCH https://graph.microsoft.com/v1.0/groups/{group-id}
Content-type: application/json

{
  "members@odata.bind": [
    "https://graph.microsoft.com/v1.0/directoryObjects/{id}",
    "https://graph.microsoft.com/v1.0/directoryObjects/{id}",
    "https://graph.microsoft.com/v1.0/directoryObjects/{id}"
    ]
}

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