Operaciones en usuarios | Referencia de API Graph
Se aplica a: API Graph | Azure Active Directory
En este tema se describe cómo realizar operaciones en usuarios que utilizan API Graph de Azure Active Directory (AD). Con API Graph de Azure AD, puede crear, leer, actualizar y eliminar usuarios. También puede consultar y modificar las relaciones de un usuario en otras entidades de directorio. Por ejemplo, puede asignar el administrador del usuario, consultar subordinados directos del usuario, administrar las pertenencias a grupos, roles de aplicación y dispositivos asignados al usuario y mucho más.
API Graph es una API de REST compatible con OData 3.0 que proporciona acceso mediante programación a objetos de directorio en Azure Active Directory, como usuarios, grupos, contactos de la organización y aplicaciones.
Importante
La funcionalidad de la API de Azure AD Graph también se encuentra disponible a través de Microsoft Graph, una API unificada que también incluye las API de otros servicios Microsoft como Outlook, OneDrive, OneNote, Planner y Office Graph, todos ellos accesibles a través de un solo punto de conexión con un solo token de acceso. Pruébelo.
Realización de operaciones REST en usuarios
Para realizar operaciones en usuarios con API Graph, debe enviar solicitudes HTTP con un método admitido (GET, POST, PATCH, PUT o DELETE) a un punto de conexión que tenga como destino la colección de recursos de usuarios, un usuario específico, una propiedad de navegación de un usuario o una función o acción que se pueda llamar en un usuario.
Las solicitudes de la API Graph usan la siguiente dirección URL básica:
https://graph.windows.net/{tenant_id}/{resource_path}?{api_version}[odata_query_parameters]
Importante
Las solicitudes enviadas a la API Graph deben tener el formato correcto, ir dirigidas a un punto de conexión y una versión de la API Graph que sean válidos y llevar en su encabezado Authorization
un token de acceso válido obtenido de Azure AD. Para más información sobre cómo crear solicitudes y recibir respuestas con la API Graph, consulte Operations Overview.
Debe especificar la ruta de acceso a recursos de forma distinta dependiendo de si tiene como destino la colección de todos los usuarios de su inquilino, un usuario individual o una propiedad de navegación de un usuario específico.
/users
tiene como destino la colección de recursos de usuario. Puede usar esta ruta de acceso a recursos para leer todos los usuarios o una lista filtrada de usuarios de su inquilino o bien para crear uno o varios usuarios nuevos en su inquilino./users/{user_id}
tiene como destino un usuario individual de su inquilino. Debe especificaruser_id
como id. de objeto (GUID) o el nombre principal de usuario (UPN) del usuario de destino. Puede usar esta ruta de acceso a recursos para obtener las propiedades declaradas de un usuario, para modificar estas o para eliminar un usuario./users/{user_id}/{property}
tiene como destino la propiedad de navegación especificada de un usuario. Se puede usar para devolver el objeto u objetos a los que hace referencia la propiedad de navegación de destino del usuario especificado. Nota: Esta forma de direccionamiento solo está disponible para lecturas./users/{user_id}/$links/{property}
tiene como destino la propiedad de navegación especificada de un usuario. Puede usar esta forma de direccionamiento tanto para leer como para modificar una propiedad de navegación. En las lecturas, los objetos a los que hace referencia la propiedad se devuelven como uno o varios vínculos en el cuerpo de respuesta. En las escrituras, los objetos se especifican como uno o varios vínculos en el cuerpo de la solicitud.
Por ejemplo, la siguiente solicitud devuelve un vínculo al administrador del usuario especificado:
GET https://graph.windows.net/myorganization/users/john@contoso.onmicrosoft.com/$links/manager?api-version=1.6
Nota: Puede usar el alias me
para establecer como destino el usuario con sesión iniciada. Para más información sobre la realización de operaciones con el alias me
, consulte Operaciones en el usuario con sesión iniciada.
Operaciones básicas en usuarios
Puede realizar operaciones básicas de creación, lectura, actualización y eliminación (CRUD) en usuarios y sus propiedades declaradas estableciendo como destino la colección de recursos de usuario o un usuario específico. En los temas siguientes verá cómo hacerlo.
Obtener usuarios
Obtiene una colección de usuarios. Puede agregar parámetros de consulta OData a la solicitud para filtrar, ordenar y paginar la respuesta. Para más información, consulte Supported Queries, Filters, and Paging Options.
Si se ejecuta correctamente, devuelve una colección de objetos User; en caso contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users",
"operation": "get users",
"showComponents": {
"codeGenerator": "true",
"tryFeature": "true"
}
}
Obtener un usuario
Obtiene un usuario especificado. Puede usar el id. de objeto (GUID) o el nombre principal de usuario (UPN) para identificar el usuario de destino.
Si se ejecuta correctamente, devuelve el objeto User del usuario especificado; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users",
"operation": "get user by id",
"showComponents": {
"codeGenerator": "true",
"tryFeature": "true"
}
}
Obtener la foto en miniatura de un usuario
Obtiene la foto en miniatura de un usuario especificado a partir de la propiedad thumbnailPhoto. Puede usar el id. de objeto (GUID) o el nombre principal de usuario (UPN) para identificar el usuario de destino.
Si se ejecuta correctamente, devuelve la foto en miniatura del usuario especificado; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
Importante: El tipo de soporte depende del tipo de imagen que se almacena en Azure AD y se devuelve en el encabezado Content-Type
; por ejemplo, image/jpeg
. Si no se puede determinar el tipo de soporte, API Graph devuelve Content-Type
de */*
. API Graph no realiza conversiones entre tipos de soporte (imagen).
{
"api": "Users",
"operation": "get user thumbnail photo",
"showComponents": {
"codeGenerator": "false",
"tryFeature": "false"
}
}
Cree un usuario (cuenta profesional o educativa)
Agrega un usuario al inquilino creando una cuenta profesional o educativa. También se conoce a estos usuarios como cuentas o usuarios de la organización. El cuerpo de la solicitud contiene las propiedades del usuario que se van a crear. Como mínimo, debe especificar las propiedades necesarias para el usuario. Opcionalmente, puede especificar cualquier otra propiedad que se pueda escribir excepto en el caso de creationType o signInNames, que únicamente tienen validez para las cuentas locales. Para agregar un usuario de la cuenta local a un inquilino de Azure Active Directory B2C, consulte Create a user (local account) (Crear un usuario (cuenta local)).
En la tabla siguiente se muestran las propiedades que son necesarias al crear un usuario.
Parámetro obligatorio | Tipo | Descripción |
---|---|---|
accountEnabled | booleano | Se establece en true si la cuenta está habilitada; de lo contrario, se establece en false. |
displayName | cadena | Nombre que se muestra en la libreta de direcciones del usuario. |
immutableId | cadena | Solo se debe especificar al crear una nueva cuenta de usuario si usa un dominio federado para la propiedad userPrincipalName (UPN) del usuario. |
mailNickname | cadena | Alias de correo del usuario. |
passwordProfile | PasswordProfile | El perfil de contraseña del usuario. |
userPrincipalName | cadena | El nombre principal de usuario (someuser@contoso.com). El nombre principal de usuario debe contener uno de los dominios comprobados para el inquilino. |
Si se ejecuta correctamente, devuelve el objeto User que se acaba de crear; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users",
"operation": "create user"
}
Crear un usuario (cuenta local)
A partir de la versión 1.6, API Graph admite la creación de usuarios de la cuenta local para inquilinos de Azure Active Directory B2C. A diferencia de los usuarios asociados a una cuenta profesional o educativa, que para el inicio de sesión requiere una dirección de correo electrónico que contenga uno de los dominios comprobados del inquilino, los usuarios de la cuenta local admiten el inicio de sesión con credenciales específicas de la aplicación; por ejemplo, con una dirección de correo electrónico de terceros o un nombre de usuario específico de la aplicación. Para más información sobre Azure Active Directory B2C, consulte la documentación de Azure Active Directory B2C.
El cuerpo de la solicitud contiene las propiedades del usuario de la cuenta local que se van a crear. Como mínimo, debe especificar las propiedades necesarias para el usuario de la cuenta local. Son algo distintas de las especificadas para las cuentas profesionales o educativas, como puede ver en la tabla siguiente. Para los usuarios de la cuenta local, la propiedad creationType debe especificarse para indicar que el usuario es una cuenta local, mientras que la propiedad signInNames debe especificarse para pasar los nombres de inicio de sesión del usuario. Además de las propiedades necesarias, puede especificar de forma opcional cualquier otra propiedad que se pueda escribir de la entidad User; sin embargo, esto suele limitarse a las propiedades de extensión definidas por la aplicación y un subconjunto de las propiedades disponibles en la entidad User. No puede asignar licencias o suscripciones a los usuarios de la cuenta local.
En la tabla siguiente se muestran las propiedades que son necesarias al crear un usuario de la cuenta local.
Parámetro obligatorio | Tipo | Descripción |
---|---|---|
accountEnabled | booleano | Se establece en true si la cuenta está habilitada; de lo contrario, se establece en false. |
creationType | cadena | Debe establecerse en "LocalAccount" para crear un usuario de la cuenta local. Nota: Se especifica como "NameCoexistence" en la versión beta. |
displayName | cadena | Nombre que se muestra en la libreta de direcciones del usuario. |
passwordProfile | PasswordProfile | El perfil de contraseña del usuario. |
signInNames | collection(SignInName) | Uno o varios registros SignInName que especifican los nombres de inicio de sesión del usuario. Cada nombre de inicio de sesión debe ser único en toda la empresa o en todo el inquilino. Nota: Se ha cambiado el nombre de alternativeSignInNamesInfo en la versión beta. |
Si se ejecuta correctamente, devuelve el objeto User que se acaba de crear; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users2",
"operation": "create local account user"
}
Actualizar un usuario
Actualice las propiedades de un usuario. Especifique cualquier propiedad User que se pueda escribir en el cuerpo de la solicitud. Solo se cambian las propiedades que especifique.
Si se ejecuta correctamente, no se devuelve ningún cuerpo de respuesta; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users",
"operation": "update user"
}
Restablecer la contraseña de un usuario
Restablezca la contraseña de un usuario. El restablecimiento de la contraseña de un usuario es un caso especial de la operación de actualización de usuario. Especifique la propiedad passwordProfile para User. La solicitud contiene un objeto PasswordProfile válido que especifica una contraseña que cumple la directiva de complejidad de contraseñas del inquilino. La directiva de contraseñas suele imponer limitaciones sobre la complejidad, la longitud y la reutilización de una contraseña. Para más información, consulte el tema PasswordProfile.
Si se ejecuta correctamente, no se devuelve ningún cuerpo de respuesta; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users2",
"operation": "reset user password"
}
Eliminar un usuario
Elimina un usuario. Es posible que los usuarios eliminados no se puedan recuperar.
Si se ejecuta correctamente, no se devuelve ningún cuerpo de respuesta; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users",
"operation": "delete user"
}
Operaciones en propiedades de navegación del usuario
Las relaciones entre un usuario y otros objetos del directorio, como el administrador del usuario, las pertenencias directas a grupos y los subordinados directos se exponen a través de las propiedades de navegación. Puede leer y, en algunos casos, modificar estas relaciones tomando como destino estas propiedades de navegación en sus solicitudes.
Obtener el administrador de un usuario
Obtiene el administrador del usuario desde la propiedad de navegación manager.
Si se ejecuta correctamente, devuelve un vínculo al User o Contact asignado como administrador del usuario; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
Nota: Puede quitar el segmento "$links" de la dirección URL para devolver el objeto User o Contact en lugar de un vínculo.
{
"api": "Users",
"operation": "get user manager link",
"showComponents": {
"codeGenerator": "true",
"tryFeature": "true"
}
}
Asignar el administrador de un usuario
Asigna el administrador de un usuario a través de la propiedad manager. Se puede asignar un usuario o un contacto. El cuerpo de la solicitud contiene un vínculo al objeto User o Contact que se va a asignar.
Si se ejecuta correctamente, no se devuelve ningún cuerpo de respuesta; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
{
"api": "Users",
"operation": "update user manager"
}
Obtener subordinados directos de un usuario
Obtiene los subordinados directos del usuario desde la propiedad de navegación directReports.
Si se ejecuta correctamente, devuelve una colección de vínculos a User y Contact para quienes se asigna este usuario como administrador; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
Nota: Puede quitar el segmento "$links" de la dirección URL para devolver los objetos DirectoryObject para los usuarios y contactos en lugar de vínculos.
{
"api": "Users",
"operation": "get user direct reports links",
"showComponents": {
"codeGenerator": "true",
"tryFeature": "true"
}
}
Obtener las pertenencias a roles de grupo y directorio de un usuario
Obtiene las pertenencias a roles de grupo y directorio del usuario desde la propiedad de navegación memberOf.
Esta propiedad devuelve solo roles de grupo o directorio de los cuales el usuario es miembro directo. Para obtener todos los grupos a los que el usuario pertenece de forma directa o transitiva, llame a la función getMemberGroups. Para obtener todos los roles de grupo o directorio a los que el usuario pertenece de forma directa o transitiva, llame a la función getMemberObjects.
Si se ejecuta correctamente, devuelve una colección de vínculos a Group y DirectoryRole de los cuales este usuario es miembro; de lo contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.
Nota: Puede quitar el segmento "$links" de la dirección URL para devolver los objetos DirectoryObject para los roles de grupo y directorio en lugar de vínculos.
{
"api": "Users",
"operation": "get user memberOf links",
"showComponents": {
"codeGenerator": "true",
"tryFeature": "true"
}
}
Otras propiedades de navegación
Gracias al uso de los mismos patrones mostrados anteriormente, puede tener como destino otras propiedades de navegación expuestas por los usuarios. Algunas propiedades son de solo lectura y otras pueden modificarse. Para más información sobre las propiedades de navegación del usuario, consulte la documentación de User.
Funciones y acciones en usuarios
Puede llamar a cualquiera de las siguientes funciones o acciones en un usuario.
Asignar una licencia a un usuario
Puede llamar a la acción assignLicense para asignar o quitar licencias de un usuario y para habilitar o deshabilitar planes específicos para el usuario.
Cambiar contraseña del usuario que inició sesión
Puede llamar a la acción changePassword en el usuario con sesión iniciada para permitirle cambiar su contraseña.
Comprobar la pertenencia a un grupo específico (transitiva)
Puede llamar a la función isMemberOf para comprobar la pertenencia a un grupo específico. La comprobación es transitiva.
Comprobar la pertenencia en una lista de grupos (transitiva)
Puede llamar a la función checkMemberGroups para comprobar la pertenencia a una lista de grupos. La comprobación es transitiva.
Obtener todas las pertenencias a grupos (transitivas)
Puede llamar a la función getMemberGroups para devolver todos los grupos de los que el usuario es miembro. La comprobación es transitiva, a diferencia de la lectura de la propiedad de navegación memberOf, que solo devuelve los grupos de los que el usuario es miembro directo.
Obtener todas las pertenencias a grupos y roles de directorio (transitiva)
Puede llamar a la función getMemberObjects para devolver todos los grupos y roles de directorio de los que el usuario es miembro. La comprobación es transitiva, a diferencia de la lectura de la propiedad de navegación memberOf, que solo devuelve los grupos de los que el usuario es miembro directo.
Get users
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)&"^
```Java
// 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
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&"^
// 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
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)
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)
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
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
Response List
Status Code | Description |
---|---|
204 | No Content. Indicates success. No response body is returned. |
Reset a user's password
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
Response List
Status Code | Description |
---|---|
204 | No Content. Indicates success. No response body is returned. |
Delete a user
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
Response List
Status Code | Description |
---|---|
204 | No Content. Indicates success. |
Invalidate all refresh tokens for a user
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
Response List
Status Code | Description |
---|---|
204 | No Content. Indicates success. No response body is returned. |
Get a user's manager
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&"^
// 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
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
Response List
Status Code | Description |
---|---|
204 | No Content. Indicates success. No response body is returned. |
Get a user's direct reports
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
{
"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&"^
// 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
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&"^
// 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
Recursos adicionales
- Aprenda más sobre las características, funcionalidades y características de la versión preliminar que se admiten en API Graph en los conceptos de la API Graph.