Condividi tramite


Operazioni sui gruppi | Informazioni di riferimento sull'API Graph

Si applica a: API Graph | Azure Active Directory

Questo argomento descrive come eseguire operazioni sui gruppi tramite l'API Graph di Azure Active Directory (Azure AD). L'API Graph di Azure AD consente di creare, leggere, aggiornare ed eliminare gruppi. È anche possibile eseguire query sui membri di un gruppo, aggiungere ed eliminare membri da un gruppo, controllare l'appartenenza di un gruppo ad altri gruppi, assegnare ruoli dell'app a un gruppo e altro ancora. Alcune operazioni sui gruppi sono transitive mentre altre sono limitate esclusivamente ai membri diretti del gruppo. Il supporto per alcune operazioni varia a seconda del tipo di gruppo, ad esempio gruppi di sicurezza, gruppi di distribuzione di posta elettronica e gruppi di sicurezza abilitati alla posta elettronica. I membri dei gruppi possono essere costituiti da utenti, contatti e altri gruppi.

L'API Graph è un'API REST conforme alla specifica OData 3.0 che fornisce accesso a livello di codice agli oggetti directory in Azure Active Directory, ad esempio utenti, gruppi, contatti aziendali e applicazioni.

Importante

La funzionalità API Graph di Azure AD è anche disponibile tramite Microsoft Graph, un'API unificata che include le API di altri servizi Microsoft, come Outlook, OneDrive, OneNote, Planner e Office Graph, a cui si può accedere mediante un unico endpoint con un singolo token di accesso.

Esecuzione di operazioni REST sui gruppi

Per eseguire operazioni sui gruppi con l'API Graph, si inviano richieste HTTP con un metodo supportato (GET, POST, PATCH, PUT o DELETE) a un endpoint che fa riferimento alla raccolta di risorse dei gruppi, a un gruppo specifico, a una proprietà di navigazione di un gruppo oppure a una funzione o azione che può essere chiamata su un gruppo. Le sezioni seguenti illustrano come specificare la destinazione e comporre le operazioni sui gruppi.

Le richieste dell'API Graph usano l'URL di base seguente:

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

Importante

Le richieste inviate all'API Graph devono presentare il formato corretto, specificare come destinazione un endpoint e una versione dell'API Graph corretti e includere nell'intestazione Authorization un token di accesso valido ottenuto da Azure AD. Per informazioni dettagliate sulla creazione di richieste e la ricezione di risposte con l'API Graph, vedere [Operations Overview].

Il percorso {resource_path} specificato sarà diverso a seconda della destinazione dell'operazione, ad esempio la raccolta di tutti i gruppi nel tenant, un singolo gruppo o una proprietà di navigazione di un gruppo specifico.

  • /groups indica che la destinazione è la raccolta di risorse dei gruppi. È possibile usare questo percorso della risorsa per eseguire la lettura di tutti i gruppi nel tenant o per creare nuovi gruppi di sicurezza nel tenant.
  • /groups/{object_id} indica che la destinazione è un singolo gruppo nel tenant. Il gruppo di destinazione viene identificato tramite il relativo ID oggetto (GUID). È possibile usare questo percorso della risorsa per ottenere le proprietà dichiarate di un gruppo, per modificarle oppure per eliminare un gruppo di sicurezza.
  • /group/{object_id}/{nav_property} indica che la destinazione è la proprietà di navigazione specificata di un gruppo. È possibile usare questo percorso per restituire gli oggetti a cui fa riferimento la proprietà di navigazione di destinazione del gruppo specificato, ad esempio i membri del gruppo. Nota: questo modello di definizione del percorso è disponibile solo per le operazioni di lettura.
  • /groups/{object_id}/$links/{nav_property} indica che la destinazione è la proprietà di navigazione specificata di un gruppo. È possibile usare questo modello di definizione del percorso per le operazioni di lettura e di modifica di una proprietà di navigazione. Per le operazioni di lettura, gli oggetti a cui fa riferimento la proprietà vengono restituiti come uno o più collegamenti nel corpo della risposta. Per le operazioni di scrittura, gli oggetti sono specificati come uno o più collegamenti nel corpo della richiesta.

La richiesta seguente, ad esempio, restituisce una raccolta di collegamenti ai membri del gruppo specificato:

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

Operazioni di base sui gruppi

È possibile eseguire operazioni di creazione, lettura, aggiornamento ed eliminazione (CRUD) sui gruppi e sulle relative proprietà dichiarate specificando come destinazione la raccolta di risorse gruppo o un gruppo specifico. Gli argomenti seguenti illustrano come fare.

L'API Graph supporta le operazioni sui gruppi come indicato di seguito:

  • Creazione (POST): solo per i gruppi di sicurezza.
  • Lettura (GET): per tutti i gruppi.
  • Aggiornamento (PATCH): solo per i gruppi di sicurezza e i gruppi di sicurezza abilitati alla posta elettronica. Non tutte le proprietà sono supportate.
  • Eliminazione (DELETE): solo per i gruppi di sicurezza.

Ottieni gruppi

Ottiene una raccolta di gruppi. È possibile aggiungere parametri di query OData alla richiesta per ordinare ed eseguire il paging della risposta. Per altre informazioni, vedere [Supported Queries, Filters, and Paging Options].

Se l'operazione riesce, restituisce una raccolta di oggetti [Group]; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

GET https://graph.windows.net/myorganization/groups?api-version

Parameters

ParameterTypeValueNotes
Query
api-versionstringThe 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.Group",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.Group",
      "objectType": "Group",
      "objectId": "c57cdc98-0dcd-4f90-a82f-c911b288bab9",
      "deletionTimestamp": null,
      "description": "Marketing Group",
      "dirSyncEnabled": null,
      "displayName": "Marketing",
      "lastDirSyncTime": null,
      "mail": null,
      "mailNickname": "cdf76b17-0734-41bc-9c24-9a7af93f3502",
      "mailEnabled": false,
      "onPremisesSecurityIdentifier": null,
      "provisioningErrors": [],
      "proxyAddresses": [],
      "securityEnabled": true
    },
    {
      "odata.type": "Microsoft.DirectoryServices.Group",
      "objectType": "Group",
      "objectId": "cc9869f0-6ac0-4d00-bc24-621a2d949d35",
      "deletionTimestamp": null,
      "description": "Engineering Group",
      "dirSyncEnabled": null,
      "displayName": "Engineering",
      "lastDirSyncTime": null,
      "mail": null,
      "mailNickname": "ef3b8cc1-721b-4452-9e30-9867d1de80ea",
      "mailEnabled": false,
      "onPremisesSecurityIdentifier": null,
      "provisioningErrors": [],
      "proxyAddresses": [],
      "securityEnabled": true
    },
    {
      "odata.type": "Microsoft.DirectoryServices.Group",
      "objectType": "Group",
      "objectId": "fc15e7ef-993f-4865-bf37-317d9b8017b8",
      "deletionTimestamp": null,
      "description": "Test Group",
      "dirSyncEnabled": null,
      "displayName": "Test",
      "lastDirSyncTime": null,
      "mail": null,
      "mailNickname": "fec6273a-20af-49ba-8129-3cbde45a0a16",
      "mailEnabled": false,
      "onPremisesSecurityIdentifier": null,
      "provisioningErrors": [],
      "proxyAddresses": [],
      "securityEnabled": true
    }
  ]
}

Response List

Status CodeDescription
200OK. 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/groups?" + 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/groups?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/groups");
		// 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/groups?' + $.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/groups";
    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/groups');
$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/groups?%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/groups?%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/groups')

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


Ottieni un gruppo

Ottiene un gruppo specificato. Specificare il gruppo usando l'ID oggetto (GUID) corrispondente.

Se l'operazione riesce, restituisce l'oggetto [Group] per il gruppo specificato; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

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

Parameters

ParameterTypeValueNotes
URL
object_idstringThe object ID (GUID) of the target group.
Query
api-versionstringThe 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/groups/f795caea-121d-49c7-8ae6-a95623add8aa?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.Group/@Element",
  "odata.type": "Microsoft.DirectoryServices.Group",
  "objectType": "Group",
  "objectId": "b4bda672-1fba-4711-8fb1-5383c40b2c14",
  "deletionTimestamp": null,
  "description": "Marketing Department",
  "dirSyncEnabled": null,
  "displayName": "Marketing",
  "lastDirSyncTime": null,
  "mail": null,
  "mailNickname": "BposMailNickName",
  "mailEnabled": false,
  "onPremisesSecurityIdentifier": null,
  "provisioningErrors": [],
  "proxyAddresses": [],
  "securityEnabled": true
}

Response List

Status CodeDescription
200OK. Indicates success. The group 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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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


Crea un gruppo

Aggiunge un gruppo di sicurezza al tenant. Il corpo della richiesta include le proprietà del gruppo da creare. Occorre specificare le proprietà necessarie per il gruppo ed è facoltativamente possibile specificare altre proprietà accessibili in scrittura.

Importante: con l'API Graph è possibile creare solo gruppi di sicurezza. Non è possibile creare gruppi di sicurezza abilitati alla posta elettronica o gruppi di distribuzione di posta elettronica.

La tabella seguente mostra le proprietà necessarie per la creazione di un gruppo.

Parametro obbligatorio Tipo Descrizione
displayName stringa Nome visualizzato nella rubrica per il gruppo.
mailEnabled boolean Deve essere false. Questo perché con l'API Graph è possibile creare solo gruppi di sicurezza puri.
mailNickname stringa Alias di posta elettronica del gruppo.
securityEnabled boolean Deve essere true. Questo perché con l'API Graph è possibile creare solo gruppi di sicurezza puri.

Se l'operazione riesce, restituisce l'oggetto [Group] appena creato; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

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

Parameters

ParameterTypeValueNotes
Query
api-versionstring

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

{
  "displayName": "Example Group",
  "mailNickname": "ExampleGroup",
  "mailEnabled": false,
  "securityEnabled": true
}

Response

Status Code:201

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/Microsoft.DirectoryServices.Group/@Element",
  "odata.type": "Microsoft.DirectoryServices.Group",
  "objectType": "Group",
  "objectId": "c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3",
  "deletionTimestamp": null,
  "description": null,
  "dirSyncEnabled": null,
  "displayName": "Example Group",
  "lastDirSyncTime": null,
  "mail": null,
  "mailNickname": "ExampleGroup",
  "mailEnabled": false,
  "onPremisesSecurityIdentifier": null,
  "provisioningErrors": [],
  "proxyAddresses": [],
  "securityEnabled": true
}

Response List

Status CodeDescription
201Created. Indicates success. The new group is returned in the response body.

Aggiorna un gruppo

Aggiorna le proprietà di un gruppo. Specificare qualsiasi proprietà [Group] accessibile in scrittura nel corpo della richiesta. Vengono modificate solo le proprietà specificate.

Importante:

  • è possibile aggiornare solo i gruppi di sicurezza e i gruppi di sicurezza abilitati alla posta elettronica.
  • Non è possibile aggiornare un gruppo da un gruppo di sicurezza a un gruppo di sicurezza abilitato alla posta elettronica o a un gruppo di distribuzione di posta elettronica.

Se l'operazione riesce, non viene restituito alcun corpo della risposta; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

PATCH https://graph.windows.net/myorganization/groups/{object_id}?api-version

Parameters

ParameterTypeValueNotes
URL
object_idstring

c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3

The object ID (GUID) of the target group.
Query
api-versionstring

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

{
  "description": "Example Security Group"
}
PATCH https://graph.windows.net/myorganization/groups/c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3?api-version=1.6

Response

Status Code:204

Content-Type: application/json

Response List

Status CodeDescription
204No Content. Indicates success. No response body is returned.

Elimina un gruppo

Elimina un gruppo. Non è possibile recuperare i gruppi eliminati.

Importante: con l'API Graph è possibile eliminare solo gruppi di sicurezza. Non è possibile eliminare gruppi di sicurezza abilitati alla posta elettronica o gruppi di distribuzione di posta elettronica.

Se l'operazione riesce, non viene restituito alcun corpo della risposta; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

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

Parameters

ParameterTypeValueNotes
URL
object_idstring

c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3

The object ID (GUID) of the target group.
Query
api-versionstring

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/groups/c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3?api-version=1.6

Response List

Status CodeDescription
204No Content. Indicates success.

Operazioni sulle proprietà di navigazione dei gruppi

Le relazioni tra un gruppo e altri oggetti nella directory, ad esempio utenti, contatti e altri gruppi che possono essere membri del gruppo, sono esposte tramite le proprietà di navigazione. È possibile leggere e, in alcuni casi, modificare queste relazioni includendo queste proprietà di navigazione nelle richieste.

Sono supportate le operazioni seguenti:

  • Lettura (GET): per tutti i gruppi.
  • Aggiornamento (POST): per i gruppi di sicurezza e i gruppi di sicurezza abilitati alla posta elettronica (solo proprietà members e owners).
  • Eliminazione (DELETE): solo gruppi di sicurezza (solo proprietà members e owners).

Ottieni membri diretti di un gruppo

Ottiene i membri diretti del gruppo dalla proprietà di navigazione members.

Se l'operazione riesce, viene restituita una raccolta di collegamenti agli oggetti User, [Contact], [ServicePrincipal] e [Group] che sono membri diretti di questo gruppo; in caso contrario il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

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

Parameters

ParameterTypeValueNotes
URL
object_idstringThe object ID (GUID) of the target group.
Query
api-versionstringThe 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/groups/f795caea-121d-49c7-8ae6-a95623add8aa/$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/06adda87-a819-4c2e-ab30-127f308468b5/Microsoft.DirectoryServices.User"
    },
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/225711c4-501c-4e38-b10c-654a4f62ad67/Microsoft.DirectoryServices.User"
    },
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/2355eace-6b1d-4560-a481-eddabb529537/Microsoft.DirectoryServices.User"
    },
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/2b0a2e75-f6f5-498a-9f5c-3543e171a5a6/Microsoft.DirectoryServices.User"
    }
  ]
}

Response List

Status CodeDescription
200OK. Indicates success. A collection of links to the group members is returned.
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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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/groups/{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


Aggiungi membri al gruppo

Aggiunge un membro a un gruppo di sicurezza o a un gruppo di sicurezza abilitato per la posta elettronica tramite la proprietà di navigazione members. È possibile aggiungere utenti, contatti, entità servizio o altri gruppi. Il corpo della richiesta contiene un singolo collegamento agli oggetti User, [Contact], [ServicePrincipal] o [Group] da aggiungere.

Importante: è possibile aggiungere membri solo ai gruppi di sicurezza e ai gruppi di sicurezza abilitati per la posta elettronica.

Se l'operazione riesce, non viene restituito alcun corpo della risposta; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

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

Parameters

ParameterTypeValueNotes
URL
object_idstring

b4bda672-1fba-4711-8fb1-5383c40b2c14

The object ID (GUID) of the target group.
Query
api-versionstring

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/groups/b4bda672-1fba-4711-8fb1-5383c40b2c14/$links/members?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status CodeDescription
204No Content. Indicates success. No response body is returned.

Elimina un membro del gruppo

Elimina un membro del gruppo specificato da un gruppo di sicurezza tramite la proprietà di navigazione members. Specificare l'ID oggetto dell'oggetto User, [Contact], [ServicePrincipal] o [Group] da eliminare le segmento terminale dell'URL.

Importante: è possibile eliminare membri solo dai gruppi di sicurezza puri.

Se l'operazione riesce, non viene restituito alcun corpo della risposta; in caso contrario, il corpo della risposta contiene i dettagli dell'errore. Per altre informazioni sugli errori, vedere [Error Codes and Error Handling].

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

Parameters

ParameterTypeValueNotes
URL
object_idstring

b4bda672-1fba-4711-8fb1-5383c40b2c14

The object ID (GUID) of the target group.
member_idstring

3eb6055a-baeb-44d4-a1ea-2fee86d8891b

The object ID (GUID) of the member to be removed. Can be a user, a contact, or a group.
Query
api-versionstring

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/groups/b4bda672-1fba-4711-8fb1-5383c40b2c14/$links/members/3eb6055a-baeb-44d4-a1ea-2fee86d8891b?api-version=1.6

Response

Status Code:204

Content-Type: application/json

none

Response List

Status CodeDescription
204No Content. Indicates success. No response body is returned.

Altre proprietà di navigazione

Usando gli stessi modelli descritti in precedenza, è possibile specificare come destinazione altre proprietà di navigazione esposte dai gruppi. Alcune proprietà sono di sola lettura, mentre altre possono essere modificate. Per altre informazioni sulle proprietà di navigazione dei gruppi, vedere la documentazione relativa agli oggetti [Group].


Funzioni e azioni sui gruppi

Su un gruppo è possibile chiamare tutte le funzioni o azioni seguenti.

Controlla l'appartenenza in un gruppo specifico (transitiva)

Chiamare la funzione [isMemberOf] per verificare l'appartenenza di un utente, un contatto, un'entità servizio o un altro gruppo in un gruppo specifico. La verifica è transitiva.

Controlla l'appartenenza in un elenco di gruppi (transitiva)

Chiamare la funzione [checkMemberGroups] per verificare l'appartenenza di un utente, un contatto, un'entità servizio o un gruppo in un elenco di gruppi. La verifica è transitiva.

Ottieni tutte le appartenenze a gruppi (transitiva)

Chiamare la funzione [getMemberGroups] per ottenere tutti i gruppi di cui un utente, un contatto, un'entità servizio o un gruppo è membro. La verifica è transitiva.

Ottieni le appartenenze a gruppi e ruoli della directory (transitiva)

Chiamare la funzione [getMemberObjects] per ottenere tutti i gruppi e i ruoli della directory di cui un utente, un contatto, un gruppo o un'entità servizio è membro. La verifica è transitiva.

Risorse aggiuntive