Operaciones en grupos | Referencia de API Graph

Se aplica a: API Graph | Azure Active Directory

En este tema se describe cómo realizar operaciones en grupos que usan API Graph de Azure Active Directory (AD). Con API Graph de Azure AD, puede crear, leer, actualizar y eliminar grupos. También puede consultar los miembros de un grupo, agregar y eliminar miembros de un grupo, comprobar la pertenencia de un grupo a otros grupos, asignar roles de aplicación a un grupo, etc. Algunas operaciones de grupo son transitivas y otras solo tienen un ámbito de miembros directos del grupo. El soporte para algunas operaciones varía entre grupos de seguridad, grupos de distribución de correo y grupos de seguridad habilitados para correo. Los grupos pueden tener usuarios, contactos y otros grupos como miembros.

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 grupos

Para realizar operaciones en grupos 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 grupos, un grupo específico, una propiedad de navegación de un grupo o una función o acción que se pueda llamar en un grupo. En las secciones siguientes se describe cómo establecer como destino y componer operaciones en grupos.

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 en función de que tenga como destino la colección de todos los grupos de su inquilino, un grupo individual o una propiedad de navegación de un grupo específico.

  • /groups tiene como destino la colección de recursos de grupo. Puede usar esta ruta de acceso a recursos para leer todos los grupos del inquilino o para crear nuevos grupos de seguridad en el inquilino.
  • /groups/{object_id} tiene como destino un grupo individual de su inquilino. Especifique el grupo de destino con su identificador (GUID) de objeto. Puede usar esta ruta de acceso a recursos para obtener las propiedades declaradas de un grupo, para modificarlas o para eliminar un grupo de seguridad.
  • /group/{object_id}/{nav_property} tiene como destino la propiedad de navegación especificada de un grupo. Se puede usar para devolver los objetos a los que hace referencia la propiedad de navegación de destino del grupo especificado; por ejemplo, los miembros del grupo. Nota: Esta forma de direccionamiento solo está disponible para lecturas.
  • /groups/{object_id}/$links/{nav_property} tiene como destino la propiedad de navegación especificada de un grupo. Puede usar esta forma de direccionamiento tanto para leer como para modificar una propiedad de navegación. En las lecturas, los objetos a los que hace referencia la propiedad se devuelven como uno o varios vínculos en el cuerpo de respuesta. En las escrituras, los objetos se especifican como uno o varios vínculos en el cuerpo de la solicitud.

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

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

Operaciones básicas en grupos

Puede realizar operaciones básicas de creación, lectura, actualización y eliminación (CRUD) en los grupos y sus propiedades declaradas dirigiéndolas a la colección de grupos de recursos o a un grupo específico. En los temas siguientes verá cómo hacerlo.

API Graph admite operaciones en grupos como sigue:

  • Create (POST): solo grupos de seguridad.
  • Read (GET): todos los grupos.
  • Update (PATCH): grupos de seguridad y grupos de seguridad habilitados para correo. No todas las propiedades se admiten.
  • Delete (DELETE): solo grupos de seguridad.

Obtener grupos

Obtiene una colección de grupos. Puede agregar parámetros de consulta de OData a la solicitud para ordenar y paginar la respuesta. Para más información, consulte Supported Queries, Filters, and Paging Options.

Si se ejecuta correctamente, devuelve una colección de objetos Group; en caso contrario, el cuerpo de respuesta contiene detalles del error. Para más información sobre los errores, consulte Error Codes and Error Handling.

{
    "api":  "Groups",
    "operation":    "get groups", 
     "showComponents": {        
        "codeGenerator": "true",
        "tryFeature": "true"      
    } 
}

Obtener un grupo

Obtiene un grupo especificado. Especifique el grupo por su identificador (GUID) de objeto.

Si se ejecuta correctamente, devuelve el objeto Group del grupo 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":  "Groups",
    "operation":    "get group by id",
     "showComponents": {        
        "codeGenerator":    "true",
        "tryFeature": "true"      
    } 
}

Crear un grupo

Agrega un grupo de seguridad al inquilino. El cuerpo de la solicitud contiene las propiedades del grupo que se va a crear. Debe especificar las propiedades necesarias para el grupo. También puede especificar otras propiedades que se puedan escribir.

Importante: Solo puede crear grupos de seguridad con API Graph. No pueden crear grupos de seguridad habilitados para correo ni grupos de distribución de correo.

En la tabla siguiente se muestran las propiedades que son necesarias al crear un grupo.

Parámetro obligatorio Tipo Descripción
displayName cadena Nombre que se muestra en la libreta de direcciones del grupo.
mailEnabled booleano Debe ser false. Esto se debe a que solo se pueden crear grupos de seguridad puros con API Graph.
mailNickname cadena Alias de correo del grupo.
securityEnabled booleano Debe ser true. Esto se debe a que solo se pueden crear grupos de seguridad puros con API Graph.

Si se ejecuta correctamente, devuelve el objeto Group 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":  "Groups",
    "operation":    "create group" 
}

Actualizar un grupo

Actualice las propiedades de un grupo. Especifique cualquier propiedad Group que se pueda escribir en el cuerpo de la solicitud. Solo se cambian las propiedades que especifique.

Importante:

  • Solo se pueden actualizar grupos de seguridad y grupos de seguridad habilitados para correo.
  • Un grupo de seguridad no se puede actualizar a un grupo de seguridad habilitado para correo ni a un grupo de distribución de correo.

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":  "Groups",
    "operation":    "update group"
}

Eliminar un grupo

Elimina un grupo. Los grupos eliminados no son recuperables.

Importante: Solo puede eliminar grupos de seguridad con API Graph. No pueden eliminar grupos de seguridad habilitados para correo ni grupos de distribución de correo.

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":  "Groups",
    "operation":    "delete group"
}

Propiedades de navegación de operaciones en grupo

Las relaciones entre un grupo y otros objetos del directorio, como los usuarios, los contactos y otros grupos que puedan ser miembros suyos se exponen a través de las propiedades de navegación. Puede leer y, en algunos casos, modificar estas relaciones tomando como destino estas propiedades de navegación en sus solicitudes.

Las operaciones se admiten de la manera siguiente:

  • Read (GET): todos los grupos.
  • Update (POST): grupos de seguridad y grupos de seguridad habilitados para correo (solo members y owners).
  • Delete (DELETE): solo grupos de seguridad (solo members y owners).

Obtener miembros directos de un grupo

Obtiene los miembros directos del grupo de la propiedad de navegación members.

Si se ejecuta correctamente, devuelve una colección de vínculos a los User, Contact, ServicePrincipal y otros Group que son miembros directos de este grupo; 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":  "Groups",
    "operation":    "get group members links",
     "showComponents": {        
        "codeGenerator":    "true",
        "tryFeature": "true"      
    } 
}

Agregar miembros del grupo

Agrega un miembro a un grupo de seguridad o a un grupo de seguridad habilitado para correo a través de la propiedad de navegación members. Puede agregar usuarios, contactos, entidades de servicio u otros grupos. El cuerpo de la solicitud contiene un solo vínculo al objeto User, Contact, ServicePrincipal o Group que se va a agregar.

Importante: Solo puede agregar miembros a grupos de seguridad y grupos de seguridad habilitados para correo.

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":  "Groups",
    "operation":    "add group members"
}

Eliminar un miembro de grupo

Elimina un miembro de grupo especificado de un grupo de seguridad a través de la propiedad de navegación members. Especifique el identificador de objeto del User, Contact, ServicePrincipal o Group que desea eliminar en el segmento de dirección URL del terminal.

Importante: Solo puede eliminar miembros de grupos de seguridad puros.

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":  "Groups",
    "operation":    "delete group member"
}

Otras propiedades de navegación

Gracias al uso de los mismos patrones mostrados anteriormente, puede establecer como destino otras propiedades de navegación expuestas por grupos. Algunas propiedades son de solo lectura y otras pueden modificarse. Para más información sobre las propiedades de navegación de grupo, consulte la documentación de Group.


Funciones y acciones en grupos

Puede llamar a cualquiera de las siguientes funciones o acciones en un grupo.

Comprobar la pertenencia a un grupo específico (transitiva)

Puede llamar a la función isMemberOf para comprobar la pertenencia de un usuario, un contacto, una entidad de servicio u otro grupo a un grupo específico. La comprobación es transitiva.

Comprobar la pertenencia en una lista de grupos (transitiva)

Puede llamar a la función checkMemberGroups para comprobar la pertenencia de un usuario, un contacto, una entidad de servicio o un grupo a una lista de grupos. La comprobación es transitiva.

Obtener todas las pertenencias a grupos (transitivas)

Puede llamar a la función getMemberGroups para devolver todos los grupos de los que un usuario, un contacto, una entidad de servicio o un grupo es miembro. La comprobación es transitiva.

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.


Get groups

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

Get a group

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

Parameters

Parameter Type Value Notes
URL
object_id string f795caea-121d-49c7-8ae6-a95623add8aa The object ID (GUID) of the target group.
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/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 Code Description
200 OK. 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

Create a group

POST https://graph.windows.net/myorganization/groups?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 ----- ----- ------
{
  "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 Code Description
201 Created. Indicates success. The new group is returned in the response body.

Update a group

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

Parameters

Parameter Type Value Notes
URL
object_id string c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3 The object ID (GUID) of the target group.
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 ----- ----- ------
{
  "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 Code|Description| |-----------|-----------| 204 No Content. Indicates success. No response body is returned.

Delete a group

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

Parameters

Parameter Type Value Notes
URL
object_id string c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3 The object ID (GUID) of the target group.
Query
api-version string 1.6 Specifies the version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
DELETE https://graph.windows.net/myorganization/groups/c7ebe5ed-b1d2-4990-88f7-892e4db2e5f3?api-version=1.6

Response

Status Code:204

Content-Type: application/json

Response List

Status Code Description
204 No Content. Indicates success.

Get a group's direct members

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

Parameters

Parameter Type Value Notes
URL
user_id string f795caea-121d-49c7-8ae6-a95623add8aa The object ID (GUID) of the target group.
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/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 Code Description
200 OK. Indicates success. A collection of links to the group 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/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

Add group members

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

Parameters

Parameter Type Value Notes
URL
user_id string b4bda672-1fba-4711-8fb1-5383c40b2c14 The object ID (GUID) of the target group.
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/groups/b4bda672-1fba-4711-8fb1-5383c40b2c14/$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 group member

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

Parameters

Parameter Type Value Notes
URL
user_id string b4bda672-1fba-4711-8fb1-5383c40b2c14 The object ID (GUID) of the target group.
member_id string 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-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/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 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.