Compartir a través de


Operaciones en dominios (versión preliminar) | Referencia de API Graph

Se aplica a: API Graph | Azure Active Directory

En este tema se describe cómo realizar operaciones en dominios que usan API Graph de Azure Active Directory (AD).

Importante

Las operaciones de dominio están actualmente en versión preliminar y solo se admiten en la versión beta de API Graph de Azure AD.

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. Tenga en cuenta que actualmente no se admiten las operaciones de dominio en Microsoft Graph; debe utilizar la API Graph de Azure AD para esta característica.

Realización de operaciones REST en dominios

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

Las solicitudes de la API Graph usan la siguiente dirección URL básica:

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

Importante

Las solicitudes enviadas a la API Graph deben tener el formato correcto, ir dirigidas a un punto de conexión y una versión de la API Graph que sean válidos y llevar en su encabezado Authorization un token de acceso válido obtenido de Azure AD. Para más información sobre cómo crear solicitudes y recibir respuestas con la API Graph, consulte Operations Overview.

Debe especificar {resource_path} de forma distinta dependiendo de si tiene como destino la colección de todos los dominios de su inquilino, un dominio individual o una propiedad de navegación de un dominio específico.

  • /domains tiene como destino la colección de recursos de dominios. Puede usar esta ruta de acceso a recursos para leer todos los dominios o una lista filtrada de dominios de su inquilino o bien para crear uno o varios dominios nuevos en su inquilino.
  • /domains({domain_name}) tiene como destino un dominio individual de su inquilino. Especifique domain-name como el nombre de dominio completo del dominio de destino entre comillas simples. Puede usar esta ruta de acceso a recursos para obtener las propiedades declaradas de un dominio, para modificar estas o para eliminar un dominio.
  • /domains({domain_name})/{nav_property} tiene como destino la propiedad de navegación especificada de un dominio. Se puede usar para devolver el objeto u objetos a los que hace referencia la propiedad de navegación de destino del dominio especificado. Nota: Esta forma de direccionamiento solo está disponible para lecturas.
  • /domains({domain_name})/$links/{nav_property} tiene como destino la propiedad de navegación especificada de un dominio. Puede usar esta forma de direccionamiento tanto para leer como para modificar una propiedad de navegación. En las lecturas, los objetos a los que hace referencia la propiedad se devuelven como uno o varios vínculos en el cuerpo de respuesta. En las escrituras, los objetos se especifican como uno o varios vínculos en el cuerpo de la solicitud.

Por ejemplo, la siguiente solicitud devuelve un vínculo al administrador del usuario especificado:

GET https://graph.windows.net/myorganization/domains('contoso.com')/serviceConfigurationRecords?api-version=beta

Importante: Las operaciones en dominios solo se admiten en la versión beta.

Operaciones básicas en dominios (versión preliminar)

Puede realizar operaciones básicas de creación, lectura, actualización y eliminación (CRUD) en dominios y sus propiedades declaradas estableciendo como destino la colección de recursos de dominio o un dominio específico. En los temas siguientes verá cómo hacerlo.

API Graph admite operaciones en grupos como sigue:

  • Create (POST): uso de dominios no comprobados y comprobado.
  • Read (GET): todos los dominios.
  • Update (PATCH): Solo dominios comprobados. No todas las propiedades se admiten.
  • Delete (DELETE): todos los dominios.

Obtener dominios (versión preliminar)

Obtiene una colección de dominios. Puede agregar parámetros de consulta OData a la solicitud para filtrar, ordenar y paginar la respuesta. Para más información, consulte Supported Queries, Filters, and Paging Options in Azure AD Graph API (Consultas, filtros y opciones de paginación admitidos con la API de Azure AD Graph).

Si se ejecuta correctamente, devuelve una colección de objetos Domain; 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":  "Domains",
    "operation":    "get domains", 
     "showComponents": {        
        "codeGenerator": "true",
        "tryFeature": "false"      
    } 
}

Obtener un dominio (versión preliminar)

Obtiene un usuario especificado. Especifique el dominio con su nombre de dominio completo.

Si se ejecuta correctamente, devuelve el objeto Domain del dominio 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":  "Domains",
    "operation":    "get a domain",
     "showComponents": {        
        "codeGenerator":    "true",
        "tryFeature": "false"      
    } 
}

Crear un dominio (versión preliminar)

Agrega un dominio al inquilino. El cuerpo de solicitud contiene la propiedad name para el nuevo dominio. Esta es la única propiedad que se puede especificar y es necesario.

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

Parámetro obligatorio Tipo Descripción
name cadena El nombre de dominio completo del nuevo dominio; por ejemplo, "contoso.com".

Importante: Si el dominio que se va a crear es un subdominio de un dominio existente comprobado del inquilino, se creará como un dominio comprobado (la propiedad isVerified es true); en caso contrario, se creará como un dominio sin comprobar (la propiedad isVerified es false).

Si se ejecuta correctamente, devuelve el objeto Domain 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":  "Domains",
    "operation":    "create domain" 
}

Actualizar un dominio (versión preliminar)

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

Importante: Solo se pueden actualizar los dominios comprobados.

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":  "Domains",
    "operation":    "update domain"
}

Eliminar un dominio (versión preliminar)

Elimina un dominio. Los dominios eliminados no son recuperables.

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":  "Domains",
    "operation":    "delete domain"
}

Operaciones en las propiedades de navegación de dominio (versión preliminar)

Las relaciones entre un dominio y otros objetos en el directorio, como sus registros de comprobación y registros de configuración de servicio, se exponen a través de las propiedades de navegación. Puede leer estas relaciones estableciendo como destino estas propiedades de navegación en sus solicitudes.

Obtener registros de comprobación de un dominio (versión preliminar)

Obtiene los registros de comprobación del dominio en la propiedad de navegación verificationDnsRecords.

No se puede usar el dominio con el inquilino de Azure AD hasta que haya comprobado correctamente que posee el dominio. Para comprobar la propiedad del dominio, primero debe recuperar un conjunto de registros de comprobación de dominio que hay que agregar al archivo de zona del dominio.

Si se ejecuta correctamente, devuelve una colección de objetos DomainDnsRecord; 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.

Nota: Puede agregar el segmento "$links" a la dirección URL para devolver los vínculos a DomainDnsRecord.

{
    "api":  "Domains",
    "operation":    "get domain verification records",
     "showComponents": {        
        "codeGenerator":    "true",
        "tryFeature": "false"      
    } 
}

Obtener registros de configuración de servicio de un dominio (versión preliminar)

Obtiene los registros de configuración de servicio del dominio de la propiedad de navegación serviceConfigurationRecords.

Después de que haya comprobado correctamente la propiedad de un dominio y haya indicado qué servicios planea utilizar con el dominio, puede solicitar a Azure AD que devuelva un conjunto de registros de DNS que necesita agregar al archivo de zona del dominio para que los servicios puedan funcionar correctamente con el dominio.

Si se ejecuta correctamente, devuelve una colección de objetos DomainDnsRecord; 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.

Nota: Puede agregar el segmento "$links" a la dirección URL para devolver los vínculos a DomainDnsRecord.

{
    "api":  "Domains",
    "operation":    "get domain service configuration records",
     "showComponents": {        
        "codeGenerator":    "true",
        "tryFeature": "false"      
    } 
}

Funciones y acciones en dominios (versión preliminar)

Puede llamar a las acciones siguientes en un dominio.

Comprobar acción (versión preliminar)

Puede llamar a la acción verify en un dominio sin comprobar (la propiedad isVerified es false) para comprobar la propiedad del dominio.


Get domains

GET https://graph.windows.net/myorganization/domains?api-version
Parameter Type Value Notes
Query
api-version string 1.6 The version of the Graph API to target. Only '1.6' is supported. Required.

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/contoso.onmicrosoft.com/$metadata#domains",
  "value": [
    {
      "authenticationType": "Managed",
      "availabilityStatus": null,
      "adminManaged": true,
      "isDefault": true,
      "isInitial": true,
      "isRoot": true,
      "isVerified": true,
      "name": "contoso.onmicrosoft.com",
      "supportedServices": [
        "Email",
        "OfficeCommunicationsOnline"
      ]
    }
  ]
}

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/domains?" + 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/domains?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/domains");
		// 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/domains?' + $.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/domains";
    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/domains');
$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/domains?%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/domains?%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/domains')

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 domain

GET https://graph.windows.net/myorganization/domains({domain_name})?api-version
Parameter Type Value Notes
URL ----- ----- ------
domain_name string 'contoso.onmicrosoft.com' The fully qualified domain name of the target domain. Must be enclosed in single quotes.
Query ----- ----- ------
api-version string 1.6 Specifies the version of the Graph API to target. Only '1.6' is supported. Required.
GET https://graph.windows.net/myorganization/domains('contoso.onmicrosoft.com')?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#domains/@Element",
  "authenticationType": "Managed",
  "availabilityStatus": null,
  "AdminManaged": true,
  "isDefault": true,
  "isInitial": true,
  "isRoot": true,
  "isVerified": true,
  "name": "contoso.onmicrosoft.com",
  "supportedServices": [
    "Email",
    "OfficeCommunicationsOnline"
  ]
}

Response List

Status Code Description
200 OK. Indicates success. The domain 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/domains({domain_name})?" + 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/domains({domain_name})?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/domains({domain_name})");
		// 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/domains({domain_name})?' + $.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/domains({domain_name})";
    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/domains({domain_name})');
$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/domains({domain_name})?%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/domains({domain_name})?%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/domains({domain_name})')

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 domain

POST https://graph.windows.net/myorganization/domains?api-version
Parameter Type Value Notes
Query
api-version string 1.6 The version of the Graph API to target. Only '1.6' is supported. Required.
Body ----- ----- ------
Content-Type: application/json ----- ----- ------
{
  "name": "contoso.com"
}

Response

Status Code:201

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/contoso.onmicrosoft.com/$metadata#domains/@Element",
  "authenticationType": "Managed",
  "availabilityStatus": null,
  "isAdminManaged": false,
  "isDefault": false,
  "isInitial": false,
  "isRoot": false,
  "isVerified": false,
  "name": "contoso.com",
  "supportedServices": []
}

Response List

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

Update a domain

PATCH https://graph.windows.net/myorganization/domains({domain_name})?api-version
Parameter Type Value Notes
URL
domain_name string 'contoso.com' The fully qualified domain name of the target domain. Must be enclosed in single quotes.
Query
api-version string 1.6 The version of the Graph API to target. Only '1.6' is supported. Required.
Body ----- ----- ------
Content-Type: application/json ----- ----- ------
{
  "isDefault": true
}
PATCH https://graph.windows.net/myorganization/domains('contoso.com')?api-version=1.6

Response

Status Code:204

Content-Type: application/json

Response List

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

Delete a domain

DELETE https://graph.windows.net/myorganization/domains({domain_name})[?api-version]
Parameter Type Value Notes
URL
domain_name string 'contoso.com' The fully qualified domain name of the target domain. Must be enclosed in single quotes.
Query
api-version string 1.6 Specifies the version of the Graph API to target. Only '1.6' is supported. Required.
DELETE https://graph.windows.net/myorganization/domains('contoso.com')?api-version=1.6

Response

Status Code:204

Content-Type: application/json

Response List

Status Code Description
204 No Content. Indicates success.

Get a domain's verification records

GET https://graph.windows.net/myorganization/domains({domain_name})/verificationDnsRecords?api-version
Parameter Type Value Notes
URL
domain_name string 'contoso.com' The fully qualified domain name of the target domain. Must be enclosed in single quotes.
Query
api-version string 1.6 The version of the Graph API to target. Only '1.6' is supported. Required.
GET https://graph.windows.net/myorganization/domains('contoso.com')/verificationDnsRecords?api-version=1.6

Response

Status Code:204

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#domainDnsRecords",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.DomainDnsTxtRecord",
      "dnsRecordId": "aceff52c-06a5-447f-ac5f-256ad243cc5c",
      "isOptional": false,
      "label": "contoso.com",
      "recordType": "Txt",
      "supportedService": null,
      "ttl": 3600,
      "text": "MS=ms86120656"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DomainDnsMxRecord",
      "dnsRecordId": "5fbde38c-0865-497f-82b1-126f596bcee9",
      "isOptional": false,
      "label": "contoso.com",
      "recordType": "Mx",
      "supportedService": null,
      "ttl": 3600,
      "mailExchange": "ms86120656.msv1.invalid",
      "preference": 32767
    }
  ]
}

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/domains({domain_name})/verificationDnsRecords?" + 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/domains({domain_name})/verificationDnsRecords?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/domains({domain_name})/verificationDnsRecords");
		// 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/domains({domain_name})/verificationDnsRecords?' + $.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/domains({domain_name})/verificationDnsRecords";
    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/domains({domain_name})/verificationDnsRecords');
$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/domains({domain_name})/verificationDnsRecords?%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/domains({domain_name})/verificationDnsRecords?%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/domains({domain_name})/verificationDnsRecords')

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 domain's service configuration records

GET https://graph.windows.net/myorganization/domains({domain_name})/serviceConfigurationRecords?api-version
Parameter Type Value Notes
URL ----- ----- ------
domain_name string 'contoso.com' The fully qualified domain name of the target domain. Must be enclosed in single quotes.
Query ----- ----- ------
api-version string 1.6 The version of the Graph API to target. Only '1.6' is supported. Required.
GET https://graph.windows.net/myorganization/domains('contoso.com')/serviceConfigurationRecords?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#domainDnsRecords",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.DomainDnsMxRecord",
      "dnsRecordId": "2b672ab0-0bee-476f-b334-be436f2449bd",
      "isOptional": false,
      "label": "contoso.com",
      "recordType": "Mx",
      "supportedService": "Email",
      "ttl": 3600,
      "mailExchange": "contoso-com.mail.protection.outlook.com",
      "preference": 0
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DomainDnsTxtRecord",
      "dnsRecordId": "62bea837-a0d7-4466-b6d9-ff6bd1db8671",
      "isOptional": false,
      "label": "contoso.com",
      "recordType": "Txt",
      "supportedServices": "Email",
      "ttl": 3600,
      "text": "v=spf1 include: spf.protection.outlook.com ~all"
    },
    {
      "odata.type": "Microsoft.DirectoryServices.DomainDnsCnameRecord",
      "dnsRecordId": "eea5ce9e-8deb-4ab7-a114-13ed6215774f",
      "isOptional": false,
      "label": "autodiscover.contoso.com",
      "recordType": "CName",
      "supportedServices": "Email",
      "ttl": 3600,
      "canonicalName": "autodiscover.outlook.com"
    }
  ]
}

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/domains({domain_name})/serviceConfigurationRecords?" + 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/domains({domain_name})/serviceConfigurationRecords?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/domains({domain_name})/serviceConfigurationRecords");
		// 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/domains({domain_name})/serviceConfigurationRecords?' + $.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/domains({domain_name})/serviceConfigurationRecords";
    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/domains({domain_name})/serviceConfigurationRecords');
$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/domains({domain_name})/serviceConfigurationRecords?%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/domains({domain_name})/serviceConfigurationRecords?%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/domains({domain_name})/serviceConfigurationRecords')

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

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

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



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

puts response.body

Recursos adicionales

  • Aprenda más sobre las características, funcionalidades y características de la versión preliminar que se admiten en API Graph en los conceptos de la API Graph.