Compartir a través de


Operaciones en roles del directorio | Referencia de API Graph

Se aplica a: API Graph | Azure Active Directory

En este tema se describe cómo realizar operaciones en roles del directorio que usan API Graph de Azure Active Directory (AD). Los roles del directorio (DirectoryRole) llevan conjuntos específicos de derechos en el directorio. Azure AD concede a los usuarios y entidades de seguridad que son miembros de un rol del directorio los derechos asociados a ese rol. Los roles de directorio de Azure AD también se conocen como roles de administrador. Para más información acerca de los roles de directorio (administrador), consulte Asignación de roles de administrador en Azure Active Directory (Azure AD).

Con la API Graph, puede leer las propiedades de los roles del directorio, consultar a miembros de un rol del directorio y agregar miembros a un rol del directorio y eliminarlos de allí. Los roles del directorio pueden tener usuarios y entidades de seguridad como miembros. Agregar grupos a roles del directorio no se admite actualmente.

En las versiones anteriores a la 1.5, todos los roles del directorio están presentes en el inquilino de forma predeterminada. En la versión 1.5 y posterior, solo el rol del directorio de los administradores de empresa está presente de forma predeterminada. Para acceder y asignar miembros a otro rol del directorio, primero debe activarlo usando la plantilla de rol del directorio correspondiente (DirectoryRoleTemplate). Para más información, consulte Activación de un rol del directorio.

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.

Realización de operaciones REST en roles del directorio

Para realizar operaciones en roles del directorio 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 roles del directorio, un roles del directorio específico, una propiedad de navegación de un rol del directorio, o una función o acción que se pueda llamar en un rol del directorio.

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 {resource_path} de forma distinta dependiendo de si tiene como destino la colección de todos los roles del directorio de su inquilino, un rol del directorio individual o una propiedad de navegación de un rol del directorio específico.

  • /directoryRoles tiene como destino la colección de recursos de roles del directorio. Puede usar esta ruta de acceso de recursos para leer todos los roles del directorio en el inquilino y, en la versión 1.5 y posteriores, para activar un rol del directorio en el inquilino.
  • /directoryRoleTemplates tiene como destino la colección de recursos de plantillas de roles del directorio. Puede usar esta ruta de acceso de recursos para leer todas las plantillas de roles del directorio disponibles en el inquilino. En la versión 1.5 y posterior, se utilizan las plantillas de roles del directorio para activar los roles del directorio.
  • /directoryRoles/{object_id} tiene como destino un rol del directorio individual de su inquilino. Especifique el rol de destino con su identificador (GUID) del objeto. Puede usar esta ruta de acceso de recursos para obtener las propiedades declaradas de un rol del directorio especificado.
  • /directoryRoles/{object_id}/members tiene como destino la propiedad de navegación members de un rol del directorio. Puede utilizarlo para devolver los usuarios y entidades de seguridad que sean miembros del rol del directorio especificado. Nota: Esta forma de direccionamiento solo está disponible para lecturas.
  • /directoryRoles/{object_id}/$links/members tiene como destino la propiedad de navegación members de un rol del directorio. Puede usar esta forma de direccionamiento tanto para leer como para modificar los miembros del rol. En las lecturas, los usuarios y las entidades de servicio a los que hace referencia la propiedad se devuelven como uno o varios vínculos en el cuerpo de respuesta. En las escrituras, los usuarios y las entidades de servicio se especifican como uno o varios vínculos en el cuerpo de la solicitud.

Por ejemplo, la solicitud siguiente devuelve una colección de vínculos a los miembros del rol del directorio especificado:

GET https://graph.windows.net/myorganization/directoryRoles/ffffffff-ffff-ffff-ffff-ffffffffffff/$links/members?api-version=1.6

Operaciones básicas en roles del directorio

Puede realizar las siguientes operaciones básicas en los roles del directorio y plantillas de roles del directorio.

  • Lea las propiedades de todos los roles del directorio o de un rol individual.
  • Lea las propiedades de todas las plantillas de roles del directorio o de una plantilla individual (versión 1.5 y posteriores).
  • Active un rol del directorio mediante una solicitud POST (versión 1.5 y posteriores).

En los temas siguientes verá cómo hacerlo.


Obtener roles del directorio

Obtiene los roles del directorio de la colección que se activan en el inquilino. (Para las versiones anteriores a 1.5, todos los roles del directorio se activaban de forma predeterminada).

Si se ejecuta correctamente, devuelve la colección de objetos DirectoryRole que están activados; 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":  "DirectoryRoles",
    "operation":    "get directory roles", 
     "showComponents": {        
        "codeGenerator": "true"
    } 
}

Obtener un rol del directorio

Obtiene un rol del directorio especificado. Especifique la función del directorio por su identificador (GUID) de objeto.

Si se ejecuta correctamente, devuelve el objeto DirectoryRole del rol 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":  "DirectoryRoles",
    "operation":    "get directory role by id",
     "showComponents": {        
        "codeGenerator":    "true"
    } 
}

Obtener plantillas de roles del directorio

Obtiene la colección de plantillas de roles del directorio que están disponibles en el inquilino. En la versión 1.5 y posterior, se utilizan las plantillas de roles del directorio para activar las funciones del directorio. No están disponibles en versiones anteriores a 1.5.

Si se ejecuta correctamente, devuelve la colección de objetos DirectoryRoleTemplate al inquilino; 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":  "DirectoryRoles",
    "operation":    "get directory role templates", 
     "showComponents": {        
        "codeGenerator": "true"
    } 
}

Activar un rol del directorio

Activa un rol del directorio en el inquilino. Disponible únicamente en la versión 1.5 y versiones más recientes. El cuerpo de solicitud contiene el identificador de objeto de la plantilla de rol del directorio para el rol del directorio que desea activar.

Nota: En las versiones anteriores a la 1.5, todos los roles del directorio están presentes en el inquilino de forma predeterminada. En la versión 1.5 y posterior, solo el rol del directorio de los administradores de empresa está presente de forma predeterminada. Para acceder y asignar miembros a otro rol del directorio, primero debe activarlo usando la plantilla de rol del directorio correspondiente (DirectoryRoleTemplate).

En la tabla siguiente se muestran las propiedades que son necesarias al activar un rol del directorio.

Parámetro obligatorio Tipo Descripción
roleTemplateId cadena La propiedad objectId de DirectoryRoleTemplate en la que está basado el rol.

Si se ejecuta correctamente, devuelve el objeto DirectoryRole 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":  "DirectoryRoles",
    "operation":    "activate directory role" 
}

Operaciones en las propiedades de navegación del rol del directorio (versión preliminar)

Las propiedades de navegación representan relaciones entre una instancia de una entidad y otros objetos del directorio. Los roles del directorio exponen una propiedad de navegación única, la propiedad members. Esta propiedad contiene los usuarios y las entidades de seguridad que se han agregado al rol del directorio. Puede leer (GET), agregar (POST) y eliminar (DELETE) miembros del rol del directorio teniendo como destino la propiedad miembros.

Obtener miembros de un rol del directorio

Obtiene los miembros del rol del directorio desde la propiedad de navegación members.

Si se ejecuta correctamente, devuelve una colección de vínculos a User y ServicePrincipal que son miembros del rol del directorio; 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 entidades de seguridad en lugar de vínculos.

{
    "api":  "DirectoryRoles",
    "operation":    "get directory role members links",
     "showComponents": {        
        "codeGenerator":    "true"
    } 
}

Agregar miembros de rol del directorio

Agrega uno o varios miembros a un rol del directorio a través de la propiedad de navegación members. Puede agregar usuarios o entidades de seguridad. El cuerpo de solicitud contiene uno o más vínculos al objeto User y ServicePrincipal que se van a agregar.

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":  "DirectoryRoles",
    "operation":    "add directory role members"
}

Eliminar un miembro de rol del directorio

Elimina un miembro especificado en un rol del directorio a través de la propiedad de navegación members. Especifique el identificador de objeto de User o ServicePrincipal para eliminar en el segmento de la dirección URL de terminal.

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":  "DirectoryRoles",
    "operation":    "delete directory role member"
}

Funciones y acciones en roles del directorio

Puede llamar a cualquiera de las siguientes funciones en roles del directorio.

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 un usuario, un contacto, un grupo o una entidad de servicio es miembro. La comprobación es transitiva para grupos (los roles del directorio no pueden tener grupos u otros roles del directorio como miembros).

Obtener objetos de una lista de identificadores de objeto

Llame a la función getObjectsByObjectIds del servicio de directorio para devolver los objetos de directorio especificados en una lista de identificadores de objeto. También puede especificar las colecciones de recursos (usuarios, grupos, etc.) en las que se debe buscar si especifica el parámetro opcional types. Por ejemplo, puede utilizar esta función para buscar los roles del directorio en la lista de identificadores de objetos devueltos por la función getMemberObjects anterior.


Get directory roles

GET https://graph.windows.net/myorganization/directoryRoles?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.

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.DirectoryRole",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRole",
      "objectType": "Role",
      "objectId": "02618ff0-e643-450d-b9b2-2f812364eb2c",
      "deletionTimestamp": null,
      "description": "Helpdesk Administrator has access to perform common helpdesk related tasks.",
      "displayName": "Helpdesk Administrator",
      "isSystem": true,
      "roleDisabled": false,
      "roleTemplateId": "729827e3-9c14-49f7-bb1b-9608f156bbb8"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRole",
      "objectType": "Role",
      "objectId": "044ca859-dc72-47cb-b466-7f6e78398979",
      "deletionTimestamp": null,
      "description": "Allows access read tasks and a subset of write tasks in the directory.",
      "displayName": "Directory Writers",
      "isSystem": true,
      "roleDisabled": false,
      "roleTemplateId": "9360feb5-f418-4baa-8175-e2a00bac4301"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRole",
      "objectType": "Role",
      "objectId": "44261f4c-b686-44c1-8997-310171ed4ca8",
      "deletionTimestamp": null,
      "description": "Allows access to various read only tasks in the directory. ",
      "displayName": "Directory Readers",
      "isSystem": true,
      "roleDisabled": false,
      "roleTemplateId": "88d8e3e3-8f55-4a1e-953a-9b9898b8876b"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRole",
      "objectType": "Role",
      "objectId": "cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8",
      "deletionTimestamp": null,
      "description": "Company Administrator role has full access to perform any operation in the company scope.",
      "displayName": "Company Administrator",
      "isSystem": true,
      "roleDisabled": false,
      "roleTemplateId": "62e90394-69f5-4237-9190-012177145e10"
    }
  ]
}

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 path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/directoryRoles?" + 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/directoryRoles?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/directoryRoles");
		// 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/directoryRoles?' + $.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/directoryRoles";
    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/directoryRoles');
$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/directoryRoles?%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/directoryRoles?%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/directoryRoles')

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 directory role

GET https://graph.windows.net/myorganization/directoryRoles/{object_id}?api-version

Parameters

Parameter Type Value Notes
URL ---- ----- -----
object_id string cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8 The object ID (GUID) of the target directory role.
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/directoryRoles/cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.DirectoryRole/@Element",
  "odata.type": "Microsoft.DirectoryServices.DirectoryRole",
  "objectType": "Role",
  "objectId": "cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8",
  "deletionTimestamp": null,
  "description": "Company Administrator role has full access to perform any operation in the company scope.",
  "displayName": "Company Administrator",
  "isSystem": true,
  "roleDisabled": false,
  "roleTemplateId": "62e90394-69f5-4237-9190-012177145e10"
}

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 path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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/directoryRoles/{object_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 directory role templates

GET https://graph.windows.net/myorganization/directoryRoleTemplates?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.

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.DirectoryRoleTemplate",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "729827e3-9c14-49f7-bb1b-9608f156bbb8",
      "deletionTimestamp": null,
      "description": "Helpdesk Administrator has access to perform common helpdesk related tasks.",
      "displayName": "Helpdesk Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "f023fd81-a637-4b56-95fd-791ac0226033",
      "deletionTimestamp": null,
      "description": "Service Support Administrator has access to perform common support tasks.",
      "displayName": "Service Support Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "b0f54661-2d74-4c50-afa3-1ec803f12efe",
      "deletionTimestamp": null,
      "description": "Billing Administrator has access to perform common billing related tasks.",
      "displayName": "Billing Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "b5468a13-3945-4a40-b0b1-5d78c2676bbf",
      "deletionTimestamp": null,
      "description": "Allows access and management of users mailboxes.",
      "displayName": "Mailbox Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "4ba39ca4-527c-499a-b93d-d9b492c50246",
      "deletionTimestamp": null,
      "description": "Allows ability to perform tier1 support tasks.",
      "displayName": "Partner Tier1 Support"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "e00e864a-17c5-4a4b-9c06-f5b95a8d5bd8",
      "deletionTimestamp": null,
      "description": "Allows ability to perform tier2 support tasks.",
      "displayName": "Partner Tier2 Support"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "88d8e3e3-8f55-4a1e-953a-9b9898b8876b",
      "deletionTimestamp": null,
      "description": "Allows access to various read only tasks in the directory. ",
      "displayName": "Directory Readers"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "29232cdf-9323-42fd-ade2-1d097af3e4de",
      "deletionTimestamp": null,
      "description": "Exchange Service Administrator.",
      "displayName": "Exchange Service Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "75941009-915a-4869-abe7-691bff18279e",
      "deletionTimestamp": null,
      "description": "Lync Service Administrator.",
      "displayName": "Lync Service Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "fe930be7-5e62-47db-91af-98c3a49a38b1",
      "deletionTimestamp": null,
      "description": "User Account Administrator has access to perform common user management related tasks.",
      "displayName": "User Account Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "9360feb5-f418-4baa-8175-e2a00bac4301",
      "deletionTimestamp": null,
      "description": "Allows access read tasks and a subset of write tasks in the directory.",
      "displayName": "Directory Writers"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "62e90394-69f5-4237-9190-012177145e10",
      "deletionTimestamp": null,
      "description": "Company Administrator role has full access to perform any operation in the company scope.",
      "displayName": "Company Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "a0b1b346-4d3e-4e8b-98f8-753987be4970",
      "deletionTimestamp": null,
      "description": "Every user is implicitly considered to be a member of the User Role.",
      "displayName": "User"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "d65e02d2-0214-4674-8e5d-766fb330e2c0",
      "deletionTimestamp": null,
      "description": "Allows creation of new email verified users.",
      "displayName": "Email Verified User Creator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "eb1d8c34-acf5-460d-8424-c1f1a6fbdb85",
      "deletionTimestamp": null,
      "description": "Allows access manage AdHoc license.",
      "displayName": "AdHoc License Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "f28a1f50-f6e7-4571-818b-6a12f2af6b6c",
      "deletionTimestamp": null,
      "description": "SharePoint Service Administrator.",
      "displayName": "SharePoint Service Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "d405c6df-0af8-4e3b-95e4-4d06e542189e",
      "deletionTimestamp": null,
      "description": "Device Users",
      "displayName": "Device Users"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "9f06204d-73c1-4d4c-880a-6edb90606fd8",
      "deletionTimestamp": null,
      "description": "Device Administrators",
      "displayName": "Device Administrators"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "9c094953-4995-41c8-84c8-3ebb9b32c93f",
      "deletionTimestamp": null,
      "description": "Device Join",
      "displayName": "Device Join"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "c34f683f-4d5a-4403-affd-6615e00e3a7f",
      "deletionTimestamp": null,
      "description": "Workplace Device Join",
      "displayName": "Workplace Device Join"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "17315797-102d-40b4-93e0-432062caca18",
      "deletionTimestamp": null,
      "description": "Compliance administrator.",
      "displayName": "Compliance Administrator"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "d29b2b05-8046-44ba-8758-1e26182fcf32",
      "deletionTimestamp": null,
      "description": "Directory Synchronization Accounts",
      "displayName": "Directory Synchronization Accounts"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DirectoryRoleTemplate",
      "objectType": "RoleTemplate",
      "objectId": "2b499bcd-da44-4968-8aec-78e1674fa64d",
      "deletionTimestamp": null,
      "description": "Allows access to read and edit device properties. ",
      "displayName": "Device Managers"
    }
  ]
}

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 path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/directoryRoleTemplates?" + 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/directoryRoleTemplates?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/directoryRoleTemplates");
		// 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/directoryRoleTemplates?' + $.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/directoryRoleTemplates";
    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/directoryRoleTemplates');
$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/directoryRoleTemplates?%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/directoryRoleTemplates?%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/directoryRoleTemplates')

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

Activate a directory role

POST https://graph.windows.net/myorganization/directoryRoles?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 ----- ----- ------
{
  "roleTemplateId": "88d8e3e3-8f55-4a1e-953a-9b9898b8876b"
}

Response

Status Code:201

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.DirectoryRole/@Element",
  "odata.type": "Microsoft.DirectoryServices.DirectoryRole",
  "objectType": "Role",
  "objectId": "ebabdd59-04ba-46f0-bd7f-bef08fe8fa9b",
  "deletionTimestamp": null,
  "description": "Allows access to various read only tasks in the directory. ",
  "displayName": "Directory Readers",
  "isSystem": true,
  "roleDisabled": false,
  "roleTemplateId": "88d8e3e3-8f55-4a1e-953a-9b9898b8876b"
}

Response List

Status Code Description
201 Created. Indicates success. The newly activated directory role is returned in the response body.

Get a directory role's members

GET https://graph.windows.net/myorganization/directoryRoles/{object_id}/$links/members?api-version

Parameters

Parameter Type Value Notes
URL
object_id string cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8 The object ID (GUID) of the target directory role
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/directoryRoles/cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8/$links/members?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/members",
  "value": [
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/f19096bf-a58c-46ba-9ffd-0344f1daecf8/Microsoft.DirectoryServices.User"
    }
  ]
}

Response List

Status Code Description
200 OK. Indicates success. A collection of links to the directory role members is 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/directoryRoles/{object_id}/$links/members?" + 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/directoryRoles/{object_id}/$links/members?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/directoryRoles/{object_id}/$links/members");
		// 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/directoryRoles/{object_id}/$links/members?' + $.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/directoryRoles/{object_id}/$links/members";
    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/directoryRoles/{object_id}/$links/members');
$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/directoryRoles/{object_id}/$links/members?%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/directoryRoles/{object_id}/$links/members?%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/directoryRoles/{object_id}/$links/members')

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

Add directory role members

POST https://graph.windows.net/myorganization/directoryRoles/{object_id}/$links/members?api-version

Parameters

Parameter Type Value Notes
URL
object_id string cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8 The object ID (GUID) of the target directory role.
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/myorganization/directoryObjects/3eb6055a-baeb-44d4-a1ea-2fee86d8891b"
}
POST https://graph.windows.net/myorganization/directoryRoles/cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8/$links/members?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 directory role member

DELETE https://graph.windows.net/myorganization/directoryRoles/{object_id}/$links/members/{member_id}?api-version

Parameters

Parameter Type Value Notes
URL
object_id string cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8 The object ID (GUID) of the target directory role.
member_id string 3eb6055a-baeb-44d4-a1ea-2fee86d8891b The object ID (GUID) of the member to be removed. Can be a user or a service principal.
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.
DELETE https://graph.windows.net/myorganization/directoryRoles/cb5d9ae9-6e2c-41a0-9194-0d4aef426ba8/$links/members/3eb6055a-baeb-44d4-a1ea-2fee86d8891b?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.

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.