Partager via


Operations on users | Graph API reference

Applies to: Graph API | Azure Active Directory

This topic discusses how to perform operations on users using the Azure Active Directory (AD) Graph API. With the Azure AD Graph API, you can create, read, update, and delete users. You can also query and modify a user's relationships to other directory entities. For example, you can assign the user's manager, query the user's direct reports, manage group memberships, app roles, and devices assigned to the user, and much more.

The Graph API is an OData 3.0 compliant REST API that provides programmatic access to directory objects in Azure Active Directory, such as users, groups, organizational contacts, and applications.

This article applies to Azure AD Graph API. For similar info related to Microsoft Graph API, see Working with users in Microsoft Graph.

Important

We strongly recommend that you use Microsoft Graph instead of Azure AD Graph API to access Azure Active Directory resources. Our development efforts are now concentrated on Microsoft Graph and no further enhancements are planned for Azure AD Graph API. There are a very limited number of scenarios for which Azure AD Graph API might still be appropriate; for more information, see the Microsoft Graph or the Azure AD Graph blog post in the Office Dev Center.

Performing REST operations on users

To perform operations on users with the Graph API, you send HTTP requests with a supported method (GET, POST, PATCH, PUT, or DELETE) to an endpoint that targets the users resource collection, a specific user, a navigation property of a user, or a function or action that can be called on a user.

Graph API requests use the following basic URL:

https://graph.windows.net/{tenant_id}/{resource_path}?{api_version}[odata_query_parameters]

Important

Requests sent to the Graph API must be well-formed, target a valid endpoint and version of the Graph API, and carry a valid access token obtained from Azure AD in their Authorization header. For more detailed information about creating requests and receiving responses with the Graph API, see Operations Overview.

You specify the resource path differently depending on whether you are targeting the collection of all users in your tenant, an individual user, or a navigation property of a specific user.

  • /users targets the user resource collection. You can use this resource path to read all users or a filtered list of users in your tenant or to create one or more new users in your tenant.
  • /users/{user_id} targets an individual user in your tenant. You specify the user_id either as the object ID (GUID) or the user principal name (UPN) of the target user. You can use this resource path to get the declared properties of a user, to modify the declared properties of a user, or to delete a user. Note: For an external user, you must specify the user’s object ID (GUID).
  • /users/{user_id}/{property} targets the specified navigation property of a user. You can use it to return the object or objects referenced by the target navigation property of the specified user. Note: This form of addressing is only available for reads.
  • /users/{user_id}/$links/{property} targets the specified navigation property of a user. You can use this form of addressing to both read and modify a navigation property. On reads, the objects referenced by the property are returned as one or more links in the response body. On writes, the objects are specified as one or more links in the request body.

For example, the following request returns a link to the specified user's manager:

GET https://graph.windows.net/myorganization/users/john@contoso.onmicrosoft.com/$links/manager?api-version=1.6

Note: You can use the me alias to target the signed-in user. For more information about performing operations using the me alias, see Operations on the Signed-in User.

Basic operations on users

You can perform basic create, read, update, and delete (CRUD) operations on users and their declared properties by targeting either the user resource collection or a specific user. The following topics show you how.

Get users

Gets a collection of users. You can add OData query parameters to the request to filter, sort, and page the response. For more information, see Supported Queries, Filters, and Paging Options.

On success, returns a collection of User objects; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

Note: Password property will be null.

GET https://graph.windows.net/myorganization/users?api-version[&$filter]

Parameters

Parameter Type Value Notes
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
$filter string startswith(displayName,'A') A filter to apply to the request. Optional. (Leave blank to omit the $filter parameter.)

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.User",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.User",
      "objectType": "User",
      "objectId": "e61ff361-5baf-41f0-b2fd-380a6a5e406a",
      "deletionTimestamp": null,
      "accountEnabled": true,
      "signInNames": [],
      "assignedLicenses": [
        {
          "disabledPlans": [],
          "skuId": "6fd2c87f-b296-42f0-b197-1e91e994b900"
        }
      ],
      "assignedPlans": [
        {
          "assignedTimestamp": "2014-10-14T02:54:57Z",
          "capabilityStatus": "Enabled",
          "service": "exchange",
          "servicePlanId": "efb87545-963c-4e0d-99df-69c6916d9eb0"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:57Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "5dbe027f-2339-4123-9542-606e4d348a72"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:57Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "e95bec33-7c88-4a70-8e19-b10bd9d0c014"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:57Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftCommunicationsOnline",
          "servicePlanId": "0feaeb32-d00e-4d66-bd5a-43b5b83db82c"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:57Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftOffice",
          "servicePlanId": "43de0ff5-c92c-492b-9116-175376d08c38"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:57Z",
          "capabilityStatus": "Enabled",
          "service": "RMSOnline",
          "servicePlanId": "bea4c11e-220a-4e6d-8eb8-8ea15d019f90"
        }
      ],
      "city": null,
      "country": null,
      "creationType": null,
      "department": null,
      "dirSyncEnabled": null,
      "displayName": "Rob Young",
      "facsimileTelephoneNumber": null,
      "givenName": "Rob",
      "immutableId": null,
      "jobTitle": null,
      "lastDirSyncTime": null,
      "mail": "roby@a830edad9050849NDA1.onmicrosoft.com",
      "mailNickname": "roby",
      "mobile": null,
      "onPremisesSecurityIdentifier": null,
      "otherMails": [],
      "passwordPolicies": "None",
      "passwordProfile": null,
      "physicalDeliveryOfficeName": null,
      "postalCode": null,
      "preferredLanguage": null,
      "provisionedPlans": [
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "exchange"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftCommunicationsOnline"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftOffice"
        }
      ],
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:roby@a830edad9050849NDA1.onmicrosoft.com"
      ],
      "sipProxyAddress": "roby@a830edad9050849NDA1.onmicrosoft.com",
      "state": null,
      "streetAddress": null,
      "surname": "Young",
      "telephoneNumber": null,
      "usageLocation": "US",
      "userPrincipalName": "roby@a830edad9050849NDA1.onmicrosoft.com",
      "userType": "Member"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.User",
      "objectType": "User",
      "objectId": "fec3faba-6a15-4e3e-8a9e-5c63f7510377",
      "deletionTimestamp": null,
      "accountEnabled": true,
      "signInNames": [],
      "assignedLicenses": [
        {
          "disabledPlans": [],
          "skuId": "6fd2c87f-b296-42f0-b197-1e91e994b900"
        }
      ],
      "assignedPlans": [
        {
          "assignedTimestamp": "2014-10-14T02:54:32Z",
          "capabilityStatus": "Enabled",
          "service": "exchange",
          "servicePlanId": "efb87545-963c-4e0d-99df-69c6916d9eb0"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:32Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "5dbe027f-2339-4123-9542-606e4d348a72"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:32Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "e95bec33-7c88-4a70-8e19-b10bd9d0c014"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:32Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftCommunicationsOnline",
          "servicePlanId": "0feaeb32-d00e-4d66-bd5a-43b5b83db82c"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:32Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftOffice",
          "servicePlanId": "43de0ff5-c92c-492b-9116-175376d08c38"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:32Z",
          "capabilityStatus": "Enabled",
          "service": "RMSOnline",
          "servicePlanId": "bea4c11e-220a-4e6d-8eb8-8ea15d019f90"
        }
      ],
      "city": "Pittsburgh",
      "country": "United States",
      "creationType": null,
      "department": "Finance",
      "dirSyncEnabled": null,
      "displayName": "Katie Jordan",
      "facsimileTelephoneNumber": null,
      "givenName": "Katie",
      "immutableId": null,
      "jobTitle": "Auditor",
      "lastDirSyncTime": null,
      "mail": "katiej@a830edad9050849NDA1.onmicrosoft.com",
      "mailNickname": "katiej",
      "mobile": null,
      "onPremisesSecurityIdentifier": null,
      "otherMails": [],
      "passwordPolicies": "None",
      "passwordProfile": null,
      "physicalDeliveryOfficeName": "12/1110",
      "postalCode": "15212",
      "preferredLanguage": "en-US",
      "provisionedPlans": [
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "exchange"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftCommunicationsOnline"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftOffice"
        }
      ],
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:katiej@a830edad9050849NDA1.onmicrosoft.com"
      ],
      "sipProxyAddress": "katiej@a830edad9050849NDA1.onmicrosoft.com",
      "state": "PA",
      "streetAddress": "30 Isabella St., Second Floor",
      "surname": "Jordan",
      "telephoneNumber": "+1 412 555 0109",
      "usageLocation": "US",
      "userPrincipalName": "katiej@a830edad9050849NDA1.onmicrosoft.com",
      "userType": "Member"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.User",
      "objectType": "User",
      "objectId": "6816d6c4-5c13-44a5-baaa-2dae2cc07461",
      "deletionTimestamp": null,
      "accountEnabled": true,
      "signInNames": [],
      "assignedLicenses": [
        {
          "disabledPlans": [],
          "skuId": "6fd2c87f-b296-42f0-b197-1e91e994b900"
        }
      ],
      "assignedPlans": [
        {
          "assignedTimestamp": "2014-10-14T02:55:27Z",
          "capabilityStatus": "Enabled",
          "service": "exchange",
          "servicePlanId": "efb87545-963c-4e0d-99df-69c6916d9eb0"
        },
        {
          "assignedTimestamp": "2014-10-14T02:55:27Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "5dbe027f-2339-4123-9542-606e4d348a72"
        },
        {
          "assignedTimestamp": "2014-10-14T02:55:27Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "e95bec33-7c88-4a70-8e19-b10bd9d0c014"
        },
        {
          "assignedTimestamp": "2014-10-14T02:55:27Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftCommunicationsOnline",
          "servicePlanId": "0feaeb32-d00e-4d66-bd5a-43b5b83db82c"
        },
        {
          "assignedTimestamp": "2014-10-14T02:55:27Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftOffice",
          "servicePlanId": "43de0ff5-c92c-492b-9116-175376d08c38"
        },
        {
          "assignedTimestamp": "2014-10-14T02:55:27Z",
          "capabilityStatus": "Enabled",
          "service": "RMSOnline",
          "servicePlanId": "bea4c11e-220a-4e6d-8eb8-8ea15d019f90"
        }
      ],
      "city": "Iselin",
      "country": "United States",
      "creationType": null,
      "department": "Sales & Marketing",
      "dirSyncEnabled": null,
      "displayName": "Pavel Bansky",
      "facsimileTelephoneNumber": null,
      "givenName": "Pavel",
      "immutableId": null,
      "jobTitle": "VP Sales",
      "lastDirSyncTime": null,
      "mail": "pavelb@a830edad9050849NDA1.onmicrosoft.com",
      "mailNickname": "pavelb",
      "mobile": null,
      "onPremisesSecurityIdentifier": null,
      "otherMails": [],
      "passwordPolicies": "None",
      "passwordProfile": null,
      "physicalDeliveryOfficeName": "19/3123",
      "postalCode": "8830",
      "preferredLanguage": null,
      "provisionedPlans": [
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "exchange"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftCommunicationsOnline"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftOffice"
        }
      ],
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:pavelb@a830edad9050849NDA1.onmicrosoft.com"
      ],
      "sipProxyAddress": "pavelb@a830edad9050849NDA1.onmicrosoft.com",
      "state": "NJ",
      "streetAddress": "101 Wood Avenue South, Suite 900",
      "surname": "Bansky",
      "telephoneNumber": "+1 732 555 0102",
      "usageLocation": "US",
      "userPrincipalName": "pavelb@a830edad9050849NDA1.onmicrosoft.com",
      "userType": "Member"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.User",
      "objectType": "User",
      "objectId": "13addec1-c5ae-47f5-a1fe-202be14b1570",
      "deletionTimestamp": null,
      "accountEnabled": true,
      "signInNames": [],
      "assignedLicenses": [
        {
          "disabledPlans": [],
          "skuId": "6fd2c87f-b296-42f0-b197-1e91e994b900"
        }
      ],
      "assignedPlans": [
        {
          "assignedTimestamp": "2014-10-14T02:54:04Z",
          "capabilityStatus": "Enabled",
          "service": "exchange",
          "servicePlanId": "efb87545-963c-4e0d-99df-69c6916d9eb0"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:04Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "5dbe027f-2339-4123-9542-606e4d348a72"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:04Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "e95bec33-7c88-4a70-8e19-b10bd9d0c014"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:04Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftCommunicationsOnline",
          "servicePlanId": "0feaeb32-d00e-4d66-bd5a-43b5b83db82c"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:04Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftOffice",
          "servicePlanId": "43de0ff5-c92c-492b-9116-175376d08c38"
        },
        {
          "assignedTimestamp": "2014-10-14T02:54:04Z",
          "capabilityStatus": "Enabled",
          "service": "RMSOnline",
          "servicePlanId": "bea4c11e-220a-4e6d-8eb8-8ea15d019f90"
        }
      ],
      "city": "Tulsa",
      "country": "United States",
      "creationType": null,
      "department": "Sales & Marketing",
      "dirSyncEnabled": null,
      "displayName": "Garth Fort",
      "facsimileTelephoneNumber": null,
      "givenName": "Garth",
      "immutableId": null,
      "jobTitle": "Web Marketing Manager",
      "lastDirSyncTime": null,
      "mail": "garthf@a830edad9050849NDA1.onmicrosoft.com",
      "mailNickname": "garthf",
      "mobile": null,
      "onPremisesSecurityIdentifier": null,
      "otherMails": [],
      "passwordPolicies": "None",
      "passwordProfile": null,
      "physicalDeliveryOfficeName": "20/1101",
      "postalCode": "74133",
      "preferredLanguage": "en-US",
      "provisionedPlans": [
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "exchange"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftCommunicationsOnline"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftOffice"
        }
      ],
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:garthf@a830edad9050849NDA1.onmicrosoft.com"
      ],
      "sipProxyAddress": "garthf@a830edad9050849NDA1.onmicrosoft.com",
      "state": "OK",
      "streetAddress": "7633 E. 63rd Place, Suite 300",
      "surname": "Fort",
      "telephoneNumber": "+1 918 555 0101",
      "usageLocation": "US",
      "userPrincipalName": "garthf@a830edad9050849NDA1.onmicrosoft.com",
      "userType": "Member"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.User",
      "objectType": "User",
      "objectId": "89efe8ed-d141-4151-a3e4-570a70022dff",
      "deletionTimestamp": null,
      "accountEnabled": true,
      "signInNames": [],
      "assignedLicenses": [
        {
          "disabledPlans": [],
          "skuId": "6fd2c87f-b296-42f0-b197-1e91e994b900"
        }
      ],
      "assignedPlans": [
        {
          "assignedTimestamp": "2014-10-14T02:53:29Z",
          "capabilityStatus": "Enabled",
          "service": "exchange",
          "servicePlanId": "efb87545-963c-4e0d-99df-69c6916d9eb0"
        },
        {
          "assignedTimestamp": "2014-10-14T02:53:29Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "5dbe027f-2339-4123-9542-606e4d348a72"
        },
        {
          "assignedTimestamp": "2014-10-14T02:53:29Z",
          "capabilityStatus": "Enabled",
          "service": "SharePoint",
          "servicePlanId": "e95bec33-7c88-4a70-8e19-b10bd9d0c014"
        },
        {
          "assignedTimestamp": "2014-10-14T02:53:29Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftCommunicationsOnline",
          "servicePlanId": "0feaeb32-d00e-4d66-bd5a-43b5b83db82c"
        },
        {
          "assignedTimestamp": "2014-10-14T02:53:29Z",
          "capabilityStatus": "Enabled",
          "service": "MicrosoftOffice",
          "servicePlanId": "43de0ff5-c92c-492b-9116-175376d08c38"
        },
        {
          "assignedTimestamp": "2014-10-14T02:53:29Z",
          "capabilityStatus": "Enabled",
          "service": "RMSOnline",
          "servicePlanId": "bea4c11e-220a-4e6d-8eb8-8ea15d019f90"
        }
      ],
      "city": "Bellevue",
      "country": "United States",
      "creationType": null,
      "department": "Sales & Marketing",
      "dirSyncEnabled": null,
      "displayName": "Janet Schorr",
      "facsimileTelephoneNumber": null,
      "givenName": "Janet",
      "immutableId": null,
      "jobTitle": "Product Marketing Manager",
      "lastDirSyncTime": null,
      "mail": "janets@a830edad9050849NDA1.onmicrosoft.com",
      "mailNickname": "janets",
      "mobile": null,
      "onPremisesSecurityIdentifier": null,
      "otherMails": [],
      "passwordPolicies": "None",
      "passwordProfile": null,
      "physicalDeliveryOfficeName": "18/2111",
      "postalCode": "98004",
      "preferredLanguage": null,
      "provisionedPlans": [
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "exchange"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftCommunicationsOnline"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "SharePoint"
        },
        {
          "capabilityStatus": "Enabled",
          "provisioningStatus": "Success",
          "service": "MicrosoftOffice"
        }
      ],
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:janets@a830edad9050849NDA1.onmicrosoft.com"
      ],
      "sipProxyAddress": "janets@a830edad9050849NDA1.onmicrosoft.com",
      "state": "WA",
      "streetAddress": "205 108th Ave. NE, Suite 400",
      "surname": "Schorr",
      "telephoneNumber": "+1 425 555 0109",
      "usageLocation": "US",
      "userPrincipalName": "janets@a830edad9050849NDA1.onmicrosoft.com",
      "userType": "Member"
    }
  ]
}

Response List

Status Code Description
200 OK. Indicates success. The results are returned in the response body.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";

			// Specify values for optional parameters, as needed
			// queryString["$filter"] = "startswith(displayName,'A')";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/users?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/users?api-version=1.6&$filter=startswith(displayName%2c%27A%27)&"^
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample {

  public static void main(String[] args) {
	HttpClient httpclient = HttpClients.createDefault();

	try
	{
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		// Specify values for path parameters (shown as {...})
		URIBuilder builder = new URIBuilder("https://graph.windows.net/myorganization/users");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		// Specify values for optional parameters, as needed
		// builder.setParameter("$filter", "startswith(displayName,'A')");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
			// Specify values for optional parameters, as needed
			// $filter: "startswith(displayName,'A')",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/users?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/users";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
	// Specify values for optional parameters, as needed
	//'$filter' => 'startswith(displayName,'A')',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/users');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

// OAuth2 is required to access this API. For more information visit:
// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
	# Specify values for optional parameters, as needed
	#'$filter': 'startswith(displayName,'A')',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
	# Specify values for optional parameters, as needed
	#'$filter': 'startswith(displayName,'A')',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/users')

uri.query = URI.encode_www_form({
	# Specify values for the following required parameters
	'api-version' => '1.6',
	# Specify values for optional parameters, as needed
	# '$filter' => 'startswith(displayName,'A')',
})

request = Net::HTTP::Get.new(uri.request_uri)

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks



response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body

Get a user

Gets a specified user. You can use either the object ID (GUID) or the user principal name (UPN) to identify the target user.

Note: For an external user, you must specify the user’s object ID (GUID). Password property will be null.

On success, returns the User object for the specified user; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

GET https://graph.windows.net/myorganization/users/{user_id}?api-version

Parameters

Parameter Type Value Notes
URL
user_id string MeganB@M365x214355.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 Specifies the version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
GET https://graph.windows.net/myorganization/users/MeganB%40M365x214355.onmicrosoft.com?api-version=1.6

Response

Status Code:200

Content-Type: application/json

"odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.User/@Element",
  "odata.type": "Microsoft.DirectoryServices.User",
  "objectType": "User",
  "objectId": "13addec1-c5ae-47f5-a1fe-202be14b1570",
  "deletionTimestamp": null,
  "accountEnabled": true,
  "signInNames": [],
  "assignedLicenses": [
    {
      "disabledPlans": [],
      "skuId": "6fd2c87f-b296-42f0-b197-1e91e994b900"
    }
  ],
  "assignedPlans": [
    {
      "assignedTimestamp": "2014-10-14T02:54:04Z",
      "capabilityStatus": "Enabled",
      "service": "exchange",
      "servicePlanId": "efb87545-963c-4e0d-99df-69c6916d9eb0"
    },
    {
      "assignedTimestamp": "2014-10-14T02:54:04Z",
      "capabilityStatus": "Enabled",
      "service": "SharePoint",
      "servicePlanId": "5dbe027f-2339-4123-9542-606e4d348a72"
    },
    {
      "assignedTimestamp": "2014-10-14T02:54:04Z",
      "capabilityStatus": "Enabled",
      "service": "SharePoint",
      "servicePlanId": "e95bec33-7c88-4a70-8e19-b10bd9d0c014"
    },
    {
      "assignedTimestamp": "2014-10-14T02:54:04Z",
      "capabilityStatus": "Enabled",
      "service": "MicrosoftCommunicationsOnline",
      "servicePlanId": "0feaeb32-d00e-4d66-bd5a-43b5b83db82c"
    },
    {
      "assignedTimestamp": "2014-10-14T02:54:04Z",
      "capabilityStatus": "Enabled",
      "service": "MicrosoftOffice",
      "servicePlanId": "43de0ff5-c92c-492b-9116-175376d08c38"
    },
    {
      "assignedTimestamp": "2014-10-14T02:54:04Z",
      "capabilityStatus": "Enabled",
      "service": "RMSOnline",
      "servicePlanId": "bea4c11e-220a-4e6d-8eb8-8ea15d019f90"
    }
  ],
  "city": "Tulsa",
  "country": "United States",
  "creationType": null,
  "department": "Sales & Marketing",
  "dirSyncEnabled": null,
  "displayName": "Garth Fort",
  "facsimileTelephoneNumber": null,
  "givenName": "Garth",
  "immutableId": null,
  "jobTitle": "Web Marketing Manager",
  "lastDirSyncTime": null,
  "mail": "garthf@a830edad9050849NDA1.onmicrosoft.com",
  "mailNickname": "garthf",
  "mobile": null,
  "onPremisesSecurityIdentifier": null,
  "otherMails": [],
  "passwordPolicies": "None",
  "passwordProfile": null,
  "physicalDeliveryOfficeName": "20/1101",
  "postalCode": "74133",
  "preferredLanguage": "en-US",
  "provisionedPlans": [
    {
      "capabilityStatus": "Enabled",
      "provisioningStatus": "Success",
      "service": "exchange"
    },
    {
      "capabilityStatus": "Enabled",
      "provisioningStatus": "Success",
      "service": "MicrosoftCommunicationsOnline"
    },
    {
      "capabilityStatus": "Enabled",
      "provisioningStatus": "Success",
      "service": "SharePoint"
    },
    {
      "capabilityStatus": "Enabled",
      "provisioningStatus": "Success",
      "service": "SharePoint"
    },
    {
      "capabilityStatus": "Enabled",
      "provisioningStatus": "Success",
      "service": "MicrosoftOffice"
    }
  ],
  "provisioningErrors": [],
  "proxyAddresses": [
    "SMTP:garthf@a830edad9050849NDA1.onmicrosoft.com"
  ],
  "sipProxyAddress": "garthf@a830edad9050849NDA1.onmicrosoft.com",
  "state": "OK",
  "streetAddress": "7633 E. 63rd Place, Suite 300",
  "surname": "Fort",
  "telephoneNumber": "+1 918 555 0101",
  "usageLocation": "US",
  "userPrincipalName": "garthf@a830edad9050849NDA1.onmicrosoft.com",
  "userType": "Member"
}

Response List

Status Code Description
200 OK. Indicates success. The user is returned in the response body.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/users/{user_id}?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/users/{user_id}?api-version=1.6&amp;"^
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample {

  public static void main(String[] args) {
	HttpClient httpclient = HttpClients.createDefault();

	try
	{
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		// Specify values for path parameters (shown as {...})
		URIBuilder builder = new URIBuilder("https://graph.windows.net/myorganization/users/{user_id}");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/users/{user_id}?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/users/{user_id}";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/users/{user_id}');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

// OAuth2 is required to access this API. For more information visit:
// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/users/{user_id}')

uri.query = URI.encode_www_form({
	# Specify values for the following required parameters
	'api-version' => '1.6',
})

request = Net::HTTP::Get.new(uri.request_uri)

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks



response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body

Get a user's thumbnail photo

Gets the thumbnail photo for a specified user from the thumbnailPhoto property. You can use either the object ID (GUID) or the user principal name (UPN) to identify the target user. Note: For an external user, you must specify the user’s object ID (GUID).

On success, returns the thumbnail photo for the specified user; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

Important: The media type depends on the image type stored in Azure AD and is returned in the Content-Type header; for example, image/jpeg. If the media type cannot be determined, the Graph API returns a Content-Type of */*. The Graph API does not convert between media (image) types.

GET https://graph.windows.net/myorganization/users/{user_id}/thumbnailPhoto?api-version
GET https://graph.windows.net/myorganization/users/MeganB%40M365x214355.onmicrosoft.com/thumbnailPhoto?api-version=1.6

Response

Status Code:200

Content-Type: image/jpeg

image data

Response List

Status Code Description
200 OK. Indicates success. The thumbnail photo is returned in the response body. Check the Content-Type header for the media type.
404 Not Found. The requested resource was not found. This can occur if the thumbnailPhoto property is not currently set for the specified user. It can also have other causes, for example, a bad domain. A code and associated message is returned with the error.

Create a user (work or school account)

Adds a user to the tenant by creating a work or school account. Such users are also known as organizational accounts or organizational users. The request body contains the properties of the user to create. At a minimum, you must specify the required properties for the user. You can optionally specify any other writable properties except for creationType, signInNames, or userIdentities, which are only valid for local and social accounts. To add a local account user to an Azure Active Directory B2C tenant, see Create a user (local account).

Important

Using scopes User.ReadWrite.All, Directory.ReadWrite.All (both of these for delegated and app only) and Directory.ActAsUser.All, the password can be set as part of user creation (POST)." Note that for the delegated permissions the signed-in user will need permissions to create users in the directory.

The following table shows the properties that are required when you create a user.

Required parameter Type Description
accountEnabled boolean true if the account is enabled; otherwise, false.
displayName string The name to display in the address book for the user.
immutableId string Only needs to be specified when creating a new user account if you are using a federated domain for the user's userPrincipalName (UPN) property.
mailNickname string The mail alias for the user.
passwordProfile PasswordProfile The password profile for the user. Note: The password can be set when creating a user.
userPrincipalName string The user principal name (someuser@contoso.com). The user principal name must contain one of the verified domains for the tenant.

On success, returns the newly created User; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

POST https://graph.windows.net/myorganization/users?api-version

Parameters

Parameter Type Value Notes
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
Body
Content-Type: application/json
{
  "accountEnabled": true,
  "displayName": "Alex Wu",
  "mailNickname": "AlexW",
  "passwordProfile": {
    "password": "Test1234",
    "forceChangePasswordNextLogin": false
  },
  "userPrincipalName": "Alex@a830edad9050849NDA1.onmicrosoft.com"
}

Response

Status Code:201

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.User/@Element",
  "odata.type": "Microsoft.DirectoryServices.User",
  "objectType": "User",
  "objectId": "84fba1e8-b942-47c9-a10e-a4bee353ce60",
  "deletionTimestamp": null,
  "accountEnabled": true,
  "signInNames": [],
  "assignedLicenses": [],
  "assignedPlans": [],
  "city": null,
  "country": null,
  "creationType": null,
  "department": null,
  "dirSyncEnabled": null,
  "displayName": "Alex Wu",
  "facsimileTelephoneNumber": null,
  "givenName": null,
  "immutableId": null,
  "jobTitle": null,
  "lastDirSyncTime": null,
  "mail": null,
  "mailNickname": "AlexW",
  "mobile": null,
  "onPremisesSecurityIdentifier": null,
  "otherMails": [],
  "passwordPolicies": null,
  "passwordProfile": null,
  "physicalDeliveryOfficeName": null,
  "postalCode": null,
  "preferredLanguage": null,
  "provisionedPlans": [],
  "provisioningErrors": [],
  "proxyAddresses": [],
  "sipProxyAddress": null,
  "state": null,
  "streetAddress": null,
  "surname": null,
  "telephoneNumber": null,
  "usageLocation": null,
  "userPrincipalName": "alex@a830edad9050849NDA1.com",
  "userType": "Member"
}

Response List

Status Code Description
201 Created. Indicates success. The new user is returned in the response body.

Create a user (local or social account)

Beginning with version 1.6, Graph API supports creating local and social account users for Azure Active Directory B2C tenants. Unlike users associated with a work or school account, which require sign-in with an email address that contains one of the tenant's verified domains, local account users support signing in with app-specific credentials; for example, with a 3rd-party email address or an app-specific user name. Social account users sign-in using popular social identity providers such as Facebook, Google, LinkedIn or Microsoft Account. For more information about Azure Active Directory B2C, see the Azure Active Directory B2C documentation.

The request body contains the properties of the local account user or social account user to create. At a minimum, you must specify the required properties. These are somewhat different than those specified for work or school accounts as you can see in the table below. For local account users, the creationType property must be specified to indicate that the user is a local account and the signInNames property must be specified to pass the sign-in names for the user. For social account users, the userIdentities collection must contain one userIdentity specifying the issuer such as facebook.com and the issuerUserId which is a unique user identifier for the issuer. For social account users, the creationType can be left null and the signInNames collection can be left empty. For a user to sign in either a local account or social account, the user creationType should be set to LocalAccount, signInNames should specify the local sign-in name for the user, and userIdentities should specify the social accounts for the user.

In addition to the required properties, you can optionally specify any other writable properties on the User entity; however, this is generally limited to app-defined extension properties and a subset of the available properties on the User entity. You cannot assign licenses or subscriptions to local account users.

The following table shows the properties that are required when you create a local account user:

Required parameter Type Description
accountEnabled boolean true if the account is enabled; otherwise, false.
creationType string Must be set to LocalAccount to create a local account user.
displayName string The name to display in the address book for the user.
passwordProfile PasswordProfile The password profile for the user.
signInNames collection(SignInName) One or more SignInName records that specify the sign-in names for the user. Each sign-in name must be unique across the company/tenant.

The following table shows the properties that are required when you create a social account user:

Required parameter Type Description
accountEnabled boolean true if the account is enabled; otherwise, false.
userIdentities collection(UserIdentity) One or more UserIdentity records that specify the social account type and the unique user identifier from the social identity provider.

On success, returns the newly created User; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

POST https://graph.windows.net/myorganization/users?api-version

Parameters

Parameter Type Value Notes
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
Body
Content-Type: application/json
{
  "accountEnabled": true,
  "creationType": "LocalAccount",
  "displayName": "Alex Wu",
  "passwordProfile": {
    "password": "Test1234",
    "forceChangePasswordNextLogin": false
  },
  "signInNames": [
    {
      "type": "userName",
      "value": "AlexW"
    },
    {
      "type": "emailAddress",
      "value": "AlexW@example.com"
    }
  ],
  "userIdentities": [
    {
      "issuer": "facebook.com",
      "issuerUserId": "MATxTNg5MzYyMzMyMNY1Njc="
    }
  ]
}

Response
Status Code:201
Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.User/@Element",
  "odata.type": "Microsoft.DirectoryServices.User",
  "objectType": "User",
  "objectId": "84fba1e8-b942-47c9-a10e-a4bee353ce60",
  "deletionTimestamp": null,
  "accountEnabled": true,
  "signInNames": [
    {
      "type": "userName",
      "value": "AlexW"
    },
    {
      "type": "emailAddress",
      "value": "AlexW@example.com"
    }
  ],
  "userIdentities": [
    {
      "issuer": "facebook.com",
      "issuerUserId": "MATxTNg5MzYyMzMyMNY1Njc="
    }
  ],
  "assignedLicenses": [],
  "assignedPlans": [],
  "city": null,
  "country": null,
  "creationType": "LocalAccount",
  "department": null,
  "dirSyncEnabled": null,
  "displayName": "Alex Wu",
  "facsimileTelephoneNumber": null,
  "givenName": null,
  "immutableId": null,
  "jobTitle": null,
  "lastDirSyncTime": null,
  "mail": null,
  "mailNickname": "AlexW_example.com#EXT#",
  "mobile": null,
  "onPremisesSecurityIdentifier": null,
  "otherMails": [],
  "passwordPolicies": null,
  "passwordProfile": null,
  "physicalDeliveryOfficeName": null,
  "postalCode": null,
  "preferredLanguage": null,
  "provisionedPlans": [],
  "provisioningErrors": [],
  "proxyAddresses": [],
  "sipProxyAddress": null,
  "state": null,
  "streetAddress": null,
  "surname": null,
  "telephoneNumber": null,
  "usageLocation": null,
  "userPrincipalName": "AlexW_example.com#EXT#@a830edad9050849NDA1.com",
  "userType": "Member"
}

Response List

Status Code Description
201 Created. Indicates success. The new user is returned in the response body.

Update a user

Update a user's properties. Specify any writable User property in the request body. Only the properties that you specify are changed.

On success, no response body is returned; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

PATCH https://graph.windows.net/myorganization/users/{user_id}?api-version

Parameters

Parameter Type Value Notes
URL
user_id string alexd@a830edad9050849NDA1.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
Body
Content-Type: application/json
{
  "department": "Sales",
  "usageLocation": "US"
}
PATCH https://graph.windows.net/myorganization/users/alexd%40a830edad9050849NDA1.onmicrosoft.com?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status Code Description
204 No Content. Indicates success. No response body is returned.

Reset a user's password

Reset a user's password. Resetting a user's password is a special case of the update user operation. Specify the passwordProfile property for the User. The request contains a valid PasswordProfile object that specifies a password that satisfies the tenant’s password complexity policy. The password policy typically imposes constraints on the complexity, length, and re-use of a password. For more information, see the PasswordProfile topic.

Important

Either delegated scope User.ReadWrite.All or Directory.AccessAsUser.All is required to reset a user's password. In addition to the correct scope, the signed-in user would need sufficient privileges to reset another user's password.

On success, no response body is returned; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

PATCH https://graph.windows.net/myorganization/users/{user_id}?api-version

Parameters

Parameter Type Value Notes
URL
user_id string alexd@a830edad9050849NDA1.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
Body
Content-Type: application/json
{
  "passwordProfile": {
    "password": "Test123456",
    "forceChangePasswordNextLogin": false
  }
}
PATCH https://graph.windows.net/myorganization/users/alexd%40a830edad9050849NDA1.onmicrosoft.com?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status Code Description
204 No Content. Indicates success. No response body is returned.

Delete a user

Deletes a user. Deleted users might not be recoverable.

On success, no response body is returned; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

DELETE https://graph.windows.net/myorganization/users/{user_id}[?api-version]

Parameters

Parameter Type Value Notes
URL
user_id string marvin@a830edad9050849NDA1.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 Specifies the version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
DELETE https://graph.windows.net/myorganization/users/marvin%40a830edad9050849NDA1.onmicrosoft.com?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status Code Description
204 No Content. Indicates success.

Invalidate all refresh tokens for a user

Invalidates all of the user's refresh tokens issued to applications (as well as session cookies in a user's browser), by resetting the refreshTokensValidFromDateTime user property to the current date-time. Typically, this operation is performed (by the user or an administrator) if the user has a lost or stolen device. This operation would prevent access to any of the organization's data accessed through applications on the device without the user first being required to sign in again. In fact, this operation would force the user to sign in again for all applications that they have previously consented to, independent of device.

For developers, if the application attempts to redeem a delegated access token for this user by using an invalidated refresh token, the application will get an error. If this happens, the application will need to acquire a new refresh token by making a request to the authorize endpoint, which will force the user to sign in.

On success, no response body is returned; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

POST https://graph.windows.net/myorganization/users/{user_id}/invalidateAllRefreshTokens?api-version

Parameters

Parameter Type Value Notes
URL
user_id string garthf@a830edad9050849NDA1.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 Specifies the version of the Graph API to target. Required.
POST https://graph.windows.net/myorganization/users/garthf%40a830edad9050849NDA1.onmicrosoft.com/invalidateAllRefreshTokens?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status Code Description
204 No Content. Indicates success. No response body is returned.

Operations on user navigation properties

Relationships between a user and other objects in the directory such as the user's manager, direct group memberships, and direct reports are exposed through navigation properties. You can read and, in some cases, modify these relationships by targeting these navigation properties in your requests.

Get a user's manager

Gets the user's manager from the manager navigation property.

On success, returns a link to the User or Contact assigned as the user's manager; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

Note: You can remove the "$links" segment from the URL to return the User or Contact object instead of a link.

GET https://graph.windows.net/myorganization/users/{user_id}/$links/manager?api-version

Parameters

Parameter Type Value Notes
URL
user_id string AdeleV@M365x214355.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
GET https://graph.windows.net/myorganization/users/AdeleV%40M365x214355.onmicrosoft.com/$links/manager?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/manager",
  "url": "https://graph.windows.net/myorganization/directoryObjects/fabeb27a-0481-4a80-b43e-a5c02c125874/Microsoft.WindowsAzure.ActiveDirectory.User"
}

Response List

Status Code Description
200 OK. Indicates success. A link to the user's manager is returned.
404 Not Found. The requested resource was not found. This can occur if the manager property is not currently set for the specified user. It can also have other causes, for example, a bad domain. A code and associated message is returned with the error.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/users/{user_id}/$links/manager?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/users/{user_id}/$links/manager?api-version=1.6&amp;"^
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample {

  public static void main(String[] args) {
	HttpClient httpclient = HttpClients.createDefault();

	try
	{
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		// Specify values for path parameters (shown as {...})
		URIBuilder builder = new URIBuilder("https://graph.windows.net/myorganization/users/{user_id}/$links/manager");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/users/{user_id}/$links/manager?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/users/{user_id}/$links/manager";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/users/{user_id}/$links/manager');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

// OAuth2 is required to access this API. For more information visit:
// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}/$links/manager?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}/$links/manager?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/users/{user_id}/$links/manager')

uri.query = URI.encode_www_form({
	# Specify values for the following required parameters
	'api-version' => '1.6',
})

request = Net::HTTP::Get.new(uri.request_uri)

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks



response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body

Assign a user's manager

Assigns a user's manager through the manager property. Either a user or a contact may be assigned. The request body contains a link to the User or Contact to assign.

On success, no response body is returned; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

PUT https://graph.windows.net/myorganization/users/{user_id}/$links/manager?api-version

Parameters

Parameter Type Value Notes
URL
user_id string alexd@a830edad9050849NDA1.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
Body
Content-Type: application/json
{
  "url": "https://graph.windows.net/contoso.onmicrosoft.com/directoryObjects/fabeb27a-0481-4a80-b43e-a5c02c125874"
}
PUT https://graph.windows.net/myorganization/users/alexd%40a830edad9050849NDA1.onmicrosoft.com/$links/manager?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status Code Description
204 No Content. Indicates success. No response body is returned.

Get a user's direct reports

Gets the user's direct reports from the directReports navigation property.

On success, returns a collection of links to the User's and Contact's for whom this user is assigned as manager; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

Note: You can remove the "$links" segment from the URL to return DirectoryObjects for the users and contacts instead of links.

GET https://graph.windows.net/myorganization/users/{user_id}/$links/directReports?api-version

Parameters

Parameter Type Value Notes
URL
user_id string MiriamG@M365x214355.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
GET https://graph.windows.net/myorganization/users/MiriamG%40M365x214355.onmicrosoft.com/$links/directReports?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/directReports",
  "value": [
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/84fba1e8-b942-47c9-a10e-a4bee353ce60/Microsoft.DirectoryServices.User"
    }
  ]
}

Response List

Status Code Description
200 OK. Indicates success. One or more direct reports are returned.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/users/{user_id}/$links/directReports?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/users/{user_id}/$links/directReports?api-version=1.6&amp;"^
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample {

  public static void main(String[] args) {
	HttpClient httpclient = HttpClients.createDefault();

	try
	{
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		// Specify values for path parameters (shown as {...})
		URIBuilder builder = new URIBuilder("https://graph.windows.net/myorganization/users/{user_id}/$links/directReports");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/users/{user_id}/$links/directReports?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/users/{user_id}/$links/directReports";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/users/{user_id}/$links/directReports');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

// OAuth2 is required to access this API. For more information visit:
// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}/$links/directReports?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}/$links/directReports?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/users/{user_id}/$links/directReports')

uri.query = URI.encode_www_form({
	# Specify values for the following required parameters
	'api-version' => '1.6',
})

request = Net::HTTP::Get.new(uri.request_uri)

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks



response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body

Get a user's group and directory role memberships

Gets the user's group and directory role memberships from the memberOf navigation property.

This property returns only groups or directory roles that the user is a direct member of. To get all of the groups that the user has direct or transitive membership in, call the getMemberGroups function. To get all of the groups or directory roles that the user has direct or transitive membership in, call the getMemberObjects function.

On success, returns a collection of links to the Group's and DirectoryRole's that this user is a member of; otherwise, the response body contains error details. For more information about errors, see Error Codes and Error Handling.

Note: You can remove the "$links" segment from the URL to return the DirectoryObjects for the groups and directory roles instead of links.

GET https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?api-version

Parameters

Parameter Type Value Notes
URL
user_id string MiriamG@M365x214355.onmicrosoft.com The user ID. Can be the object ID (GUID) or the user principal name (someuser@a830edad9050849NDA1.onmicrosoft.com) of the target user.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
GET https://graph.windows.net/myorganization/users/MiriamG%40M365x214355.onmicrosoft.com/$links/memberOf?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/memberOf",
  "value": [
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/12345678-b942-47c9-a10e-a4bee353ce60/Microsoft.DirectoryServices.Group"
    }
  ]
}

Response List

Status Code Description
200 OK. Indicates success. One or more groups and/or directory roles are returned.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            /* OAuth2 is required to access this API. For more information visit:
               https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks */



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?api-version=1.6&amp;"^
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class JavaSample {

  public static void main(String[] args) {
	HttpClient httpclient = HttpClients.createDefault();

	try
	{
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		// Specify values for path parameters (shown as {...})
		URIBuilder builder = new URIBuilder("https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

// OAuth2 is required to access this API. For more information visit:
// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}/$links/memberOf?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/users/{user_id}/$links/memberOf?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/users/{user_id}/$links/memberOf')

uri.query = URI.encode_www_form({
	# Specify values for the following required parameters
	'api-version' => '1.6',
})

request = Net::HTTP::Get.new(uri.request_uri)

# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks



response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    http.request(request)
end

puts response.body

Other navigation properties

By using the same patterns shown above, you can target other navigation properties exposed by users. Some properties are read-only and others may be modified. For more information about user navigation properties, see the documentation for User.


Functions and actions on users

You can call any of the following functions or actions on a user.

Assign a license to a user

You can call the assignLicense action to assign or remove licenses for a user and to enable or disable specific plans for the user.

Change password of the signed-in user

You can call the changePassword action on the signed-in user to enable them to change their password.

Check membership in a specific group (transitive)

You can call the isMemberOf function to check for membership in a specific group. The check is transitive.

Check membership in a list of groups (transitive)

You can call the checkMemberGroups function to check for membership in a list of groups. The check is transitive.

Get all group memberships (transitive)

You can call the getMemberGroups function to return all the groups that the user is a member of. The check is transitive, unlike reading the memberOf navigation property, which returns only the groups that the user is a direct member of.

Get all group and directory role memberships (transitive)

You can call the getMemberObjects function to return all of the groups and directory roles that the user is a member of. The check is transitive, unlike reading the memberOf navigation property, which returns only the groups that the user is a direct member of.


Additional Resources

  • Learn more about Graph API supported features, capabilities, and preview features in Graph API concepts