Операции с контактами | Справочник по API Graph

Область применения: API Graph | Azure Active Directory

В этом разделе описывается, как выполнять операции с контактами организации, используя API Graph Azure Active Directory (AD). Контакты организации обычно представляют собой пользователей, которые не являются сотрудниками вашей компании или организации. Они отличаются от личных контактов в Outlook Office 365. С помощью API Graph Azure AD можно считывать контакты организации и их связи с другими объектами каталога, включая руководителей, подчиненных и членство в группах. Запись доступна только для тех контактов организации, которые еще не синхронизировались из локального каталога (свойство dirSyncEnabled имеет значение null или false). В таких контактах можно обновлять и удалить как сами контакты, так и их свойство manager. Создавать контакты организации с помощью API Graph нельзя. Дополнительные сведения о контактах организации, включая процесс их создания в клиенте, см. в статье [Contact].

API Graph — это интерфейс прикладного программирования на основе REST, который предоставляет программный доступ к объектам каталога в Azure Active Directory, таким как пользователи, группы, контакты организации и приложения.

Важно!

Доступ к функциональным возможностям API Graph Azure AD можно получить и через Microsoft Graph — универсальный API, который также включает API других служб Майкрософт, таких как Outlook, OneDrive, OneNote, Планировщик и Office Graph, и позволяет получать к ним доступ через единую конечную точку с маркером единого доступа.

Выполнение операций REST с контактами

Для выполнения операций с контактами с использованием API Graph вы отправляете HTTP-запросы с поддерживаемым методом (обычно это GET, POST, PATCH, PUT или DELETE) к конечной точке, ориентированной на коллекцию ресурсов контактов, отдельный контакт, свойство навигации контакта либо функцию или действие, которые могут быть вызваны для контакта.

В запросах API Graph используется следующий базовый URL-адрес:

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

Важно!

Запросы, отправляемые в API Graph, должны иметь правильный формат, обращаться к действительной конечной точке и версии API Graph и содержать в заголовке Authorization действительный токен доступа, полученный из Azure AD. Более подробные сведения о создании запросов и получении ответов с помощью API Graph см. в статье [Operations Overview].

Параметр {resource_path} указывается по-разному в зависимости от того, к чему вы обращаетесь — к коллекции всех контактов в клиенте, отдельному контакту или свойству навигации определенного контакта.

  • /contacts обращается к коллекции ресурсов контактов. Этот путь можно использовать для всех контактов или отфильтрованного списка контактов в клиенте.
  • /contacts/{object_id} обращается к отдельному контакту в клиенте. Целевой контакт указывается с помощью соответствующего идентификатора объекта (GUID). Этот путь можно использовать для получения объявленных свойств контакта. Для контактов, не синхронизированных из локального каталога, этот путь можно использовать для изменения объявленных свойств контакта или для его удаления.
  • /contacts/{object_id}/{nav_property} обращается к определенному свойству навигации контакта. Этот путь можно использовать для получения объекта или объектов, на которые ссылается целевое свойство навигации указанного контакта. Примечание. Эта форма адресации доступна только для операций чтения.
  • /contacts/{object_id}/$links/{nav_property} обращается к определенному свойству навигации контакта. Эту форму адресации можно использовать для чтения и изменения свойства навигации. При чтении объекты, на которые ссылается свойство, возвращаются в виде одной или нескольких ссылок в тексте ответа. Изменять свойство навигации manager можно только для контактов, не синхронизированных из локального каталога. Свойство manager задается в тексте запроса в виде ссылки.

Например, следующий запрос возвращает ссылку на указанное свойство manager контакта:

GET https://graph.windows.net/myorganization/contacts/a2fb3752-08b4-413d-af6f-1d99c4c131d9/$links/manager?api-version=1.6

Основные операции с контактами

Операции чтения контактов можно выполнять, обращаясь к коллекции ресурсов контактов или отдельному контакту. Обновлять и удалять можно только контакты, не синхронизированные из локального каталога. Для выполнения таких операций осуществляется обращение к определенному контакту. API Graph не поддерживает создание контактов, а также обновление или удаление контактов, синхронизированных из локального каталога (свойство dirSyncEnabled имеет значение true). В следующих разделах показано, как выполнять основные операции с контактами.


Получение контактов

Возвращает коллекцию контактов. Можно добавлять параметры запросов OData для фильтрации и сортировки ответов, а также их разбиения на страницы. Дополнительные сведения см. в статье [Supported Queries, Filters, and Paging Options].

При успешном выполнении возвращает коллекцию объектов [Contact]; в противном случае текст ответа содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

{
    "api":  "Contacts",
    "operation":    "get contacts", 
     "showComponents": {        
        "codeGenerator": "true"
    } 
}

Получение контакта

Получает указанный контакт. Для обозначения целевого контакта используется соответствующий идентификатор объекта (GUID).

При успешном выполнении возвращает объект [Contact] для указанного контакта; в противном случае текст ответа содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

{
    "api":  "Contacts",
    "operation":    "get contact by id",
     "showComponents": {        
        "codeGenerator":    "true"
    } 
}

Обновление контакта

Обновляет свойства контакта. В тексте запроса укажите любое доступное для записи свойство [Contact]. Изменяются только заданные вами свойства. Обновлять можно только контакты, не синхронизированные из локального каталога (свойство dirSyncEnabled имеет значение null или false).

При успешном выполнении текст ответа не возвращается; в противном случае он содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

{
    "api":  "Contacts",
    "operation":    "update contact"
}

Удаление контакта

Удаляет контакт. Удалять можно только контакты, не синхронизированные из локального каталога (свойство dirSyncEnabled имеет значение null или false).

При успешном выполнении текст ответа не возвращается; в противном случае он содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

{
    "api":  "Contacts",
    "operation":    "delete contact"
}

Операции со свойствами навигации контактов

Отношения между контактом и другими объектами в каталоге, такими как руководитель контакта, членство в группах и подчиненные, предоставляются с помощью свойств навигации. Это отношения можно считывать и в некоторых случаях изменять, обращаясь к этим свойствам навигации в запросах.

Получение руководителя контакта

Возвращает руководителя контакта из свойства навигации manager.

При успешном выполнении возвращает ссылку [User] или [Contact] назначенного руководителем контакта; в противном случае текст ответа содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

Примечание. Чтобы вместо ссылки получить объект [User] или [Contact], можно удалить из URL-адреса сегмент "$links".

{
    "api":  "Contacts",
    "operation":    "get contact manager link",
     "showComponents": {        
        "codeGenerator":    "true",
    } 
}

Назначение руководителя контакта

Назначает руководителя контакта с помощью свойства manager. Назначаться может пользователь или контакт. Текст запроса содержит ссылку на [User] или [Contact] для назначения. Обновлять руководителей можно только для контактов, не синхронизированных из локального каталога (свойство dirSyncEnabled имеет значение null или false).

При успешном выполнении текст ответа не возвращается; в противном случае он содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

{
    "api":  "Contacts",
    "operation":    "update contact manager"
}

Получение подчиненных контакта

Получает подчиненных контакта из свойства навигации directReports.

При успешном выполнении возвращает коллекцию ссылок на объекты [User] и [Contact], для которых этот контакт назначается руководителем; в противном случае текст ответа содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

Примечание. Чтобы вместо ссылки получить объект [DirectoryObject] для пользователей и контактов, можно удалить из URL-адреса сегмент "$links".

{
    "api":  "Contacts",
    "operation":    "get contact direct reports links",
     "showComponents": {        
        "codeGenerator":    "true"
    } 
}

Получение данных о членстве контакта в группах

Возвращает данные о членстве контакта в группах из свойства навигации memberOf.

Это свойство возвращает только группы, в которые входит контакт. Чтобы получить все группы, прямым или транзитивным членом которых является контакт, вызовите функцию [getMemberGroups].

При успешном выполнении возвращает коллекцию ссылок на объекты [Group], в которые входит контакт; в противном случае текст ответа содержит сведения об ошибке. Дополнительные сведения об ошибках см. в статье Error Codes and Error Handling.

Примечание. Чтобы вместо ссылки получить объект [DirectoryObject] для групп, можно удалить из URL-адреса сегмент "$links".

{
    "api":  "Contacts",
    "operation":    "get contact memberOf links",
     "showComponents": {        
        "codeGenerator":    "true"
    } 
}

Функции и действия с контактами

Для контакта можно вызывать любую из перечисленных ниже функций.

Проверка членства в определенной группе (транзитивно)

Функция [isMemberOf] позволяет проверять членство в определенной группе. Проверка является транзитивной.

Проверка членства в списке групп (транзитивно)

Функция [checkMemberGroups] позволяет проверять членство в списке групп. Проверка является транзитивной.

Получение всех членств в группах (транзитивно)

Функция [getMemberGroups] возвращает список всех групп, в которые входит контакт. В отличие от чтения свойства навигации memberOf, которое возвращает только те группы, в которых контакт является прямым членом, данная проверка является транзитивной.


Дополнительные ресурсы

  • Дополнительные сведения о функциях, возможностях и предварительных версиях функций в Graph API см. в статье Основные понятия API Graph.

Get contacts

GET https://graph.windows.net/myorganization/contacts?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.Contact",
  "value": [
    {
      "odata.type": "Microsoft.DirectoryServices.Contact",
      "objectType": "Contact",
      "objectId": "31944231-fd52-4a7f-b32e-7902a01fddf9",
      "deletionTimestamp": null,
      "city": null,
      "companyName": null,
      "country": null,
      "department": null,
      "dirSyncEnabled": null,
      "displayName": "Marcus Breyer",
      "facsimileTelephoneNumber": null,
      "givenName": "Marcus",
      "jobTitle": null,
      "lastDirSyncTime": null,
      "mail": "Marcus@contoso.com",
      "mailNickname": "MarcusBreyer",
      "mobile": null,
      "physicalDeliveryOfficeName": null,
      "postalCode": null,
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:Marcus@contoso.com"
      ],
      "sipProxyAddress": null,
      "state": null,
      "streetAddress": null,
      "surname": "Breyer",
      "telephoneNumber": null
    },
    {
      "odata.type": "Microsoft.DirectoryServices.Contact",
      "objectType": "Contact",
      "objectId": "35110b16-360c-4c4a-93b2-03f065fabd93",
      "deletionTimestamp": null,
      "city": null,
      "companyName": null,
      "country": null,
      "department": null,
      "dirSyncEnabled": null,
      "displayName": "Yossi Ran",
      "facsimileTelephoneNumber": null,
      "givenName": "Yossi",
      "jobTitle": null,
      "lastDirSyncTime": null,
      "mail": "Yossi@contoso.com",
      "mailNickname": "YossiRan",
      "mobile": null,
      "physicalDeliveryOfficeName": null,
      "postalCode": null,
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:Yossi@contoso.com"
      ],
      "sipProxyAddress": null,
      "state": null,
      "streetAddress": null,
      "surname": "Ran",
      "telephoneNumber": null
    },
    {
      "odata.type": "Microsoft.DirectoryServices.Contact",
      "objectType": "Contact",
      "objectId": "7163f3b8-70c9-43d2-b9e1-4467ddaf087a",
      "deletionTimestamp": null,
      "city": null,
      "companyName": null,
      "country": null,
      "department": null,
      "dirSyncEnabled": null,
      "displayName": "Jeremy Nelson",
      "facsimileTelephoneNumber": null,
      "givenName": "Jeremy",
      "jobTitle": null,
      "lastDirSyncTime": null,
      "mail": "Jeremy@contoso.com",
      "mailNickname": "JeremyNelson",
      "mobile": null,
      "physicalDeliveryOfficeName": null,
      "postalCode": null,
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:Jeremy@contoso.com"
      ],
      "sipProxyAddress": null,
      "state": null,
      "streetAddress": null,
      "surname": "Nelson",
      "telephoneNumber": null
    },
    {
      "odata.type": "Microsoft.DirectoryServices.Contact",
      "objectType": "Contact",
      "objectId": "83234b5c-3a10-4108-8f36-39b1addadfdb",
      "deletionTimestamp": null,
      "city": null,
      "companyName": null,
      "country": null,
      "department": null,
      "dirSyncEnabled": null,
      "displayName": "David Strome",
      "facsimileTelephoneNumber": null,
      "givenName": "David",
      "jobTitle": null,
      "lastDirSyncTime": null,
      "mail": "David@contoso.com",
      "mailNickname": "DavidStrome",
      "mobile": null,
      "physicalDeliveryOfficeName": null,
      "postalCode": null,
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:David@contoso.com"
      ],
      "sipProxyAddress": null,
      "state": null,
      "streetAddress": null,
      "surname": "Strome",
      "telephoneNumber": null
    },
    {
      "odata.type": "Microsoft.DirectoryServices.Contact",
      "objectType": "Contact",
      "objectId": "8c1315ce-bf6f-4e26-b24f-c830606ef41c",
      "deletionTimestamp": null,
      "city": null,
      "companyName": null,
      "country": null,
      "department": null,
      "dirSyncEnabled": null,
      "displayName": "Holly Holt",
      "facsimileTelephoneNumber": null,
      "givenName": "Holly",
      "jobTitle": null,
      "lastDirSyncTime": null,
      "mail": "Holly@contoso.com",
      "mailNickname": "HollyHolt",
      "mobile": null,
      "physicalDeliveryOfficeName": null,
      "postalCode": null,
      "provisioningErrors": [],
      "proxyAddresses": [
        "SMTP:Holly@contoso.com"
      ],
      "sipProxyAddress": null,
      "state": null,
      "streetAddress": null,
      "surname": "Holt",
      "telephoneNumber": null
    }
  ]
}

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

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 contact

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

Parameters

Parameter Type Value Notes
URL
object_id string 31944231-fd52-4a7f-b32e-7902a01fddf9 The object ID (GUID) of the target contact.
Query
api-version string 1.6 Specifies the version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
GET https://graph.windows.net/myorganization/contacts/31944231-fd52-4a7f-b32e-7902a01fddf9?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/graphdir1.onmicrosoft.com/$metadata#directoryObjects/Microsoft.DirectoryServices.Contact/@Element",
  "odata.type": "Microsoft.DirectoryServices.Contact",
  "objectType": "Contact",
  "objectId": "31944231-fd52-4a7f-b32e-7902a01fddf9",
  "deletionTimestamp": null,
  "city": null,
  "companyName": null,
  "country": null,
  "department": null,
  "dirSyncEnabled": null,
  "displayName": "Marcus Breyer",
  "facsimileTelephoneNumber": null,
  "givenName": "Marcus",
  "jobTitle": null,
  "lastDirSyncTime": null,
  "mail": "Marcus@contoso.com",
  "mailNickname": "MarcusBreyer",
  "mobile": null,
  "physicalDeliveryOfficeName": null,
  "postalCode": null,
  "provisioningErrors": [],
  "proxyAddresses": [
    "SMTP:Marcus@contoso.com"
  ],
  "sipProxyAddress": null,
  "state": null,
  "streetAddress": null,
  "surname": "Breyer",
  "telephoneNumber": null
}

Response List

Status Code Description
200 OK. Indicates success. The contact 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/contacts/{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/contacts/{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/contacts/{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/contacts/{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/contacts/{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/contacts/{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/contacts/{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/contacts/{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/contacts/{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

Update a contact

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

Parameters

Parameter Type Value Notes
URL
object_id string 7163f3b8-70c9-43d2-b9e1-4467ddaf087a The object ID (GUID) of the target contact.
Query
api-version string 1.6 The version of the Graph API to target. Beginning with version 1.5, the api-version string is represented in major.minor format. Prior releases were represented as date strings: '2013-11-08' and '2013-04-05'. Required.
Body
Content-Type: application/json
{
  "department": "Sales",
  "jobTitle": "Sales Rep"
}
PATCH https://graph.windows.net/myorganization/contacts/7163f3b8-70c9-43d2-b9e1-4467ddaf087a?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 contact

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

Parameters

Parameter Type Value Notes
URL
object_id string 7163f3b8-70c9-43d2-b9e1-4467ddaf087a The object ID (GUID) of the target contact.
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/contacts/7163f3b8-70c9-43d2-b9e1-4467ddaf087a?api-version=1.6

Response

Status Code:204

Content-Type: application/json

Response List

Status Code Description
204 No Content. Indicates success.

Get a contact's manager

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

Parameters

Parameter Type Value Notes
URL
object_id string 31944231-fd52-4a7f-b32e-7902a01fddf9 The object ID (GUID) of the target contact.
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/contacts/31944231-fd52-4a7f-b32e-7902a01fddf9/$links/manager?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/manager",
  "url": "https://graph.windows.net/myorganization/directoryObjects/35110b16-360c-4c4a-93b2-03f065fabd93/Microsoft.WindowsAzure.ActiveDirectory.Contact"
}

Response List

Status Code Description
200 OK. Indicates success. A link to the contact's manager is returned.
404 Not Found. The requested resource was not found. This can occur if the manager property is not currently set for the specified contact. It can also have other causes, for example, a bad domain. A code and associated message is returned with the error.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

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



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager?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/contacts/{object_id}/$links/manager");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

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

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

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

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/contacts/{object_id}/$links/manager?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

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

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/contacts/{object_id}/$links/manager?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager')

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

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

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



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

puts response.body

Assign a contact's manager

PUT https://graph.windows.net/myorganization/contacts/{object_id}/$links/manager?api-version

Parameters

Parameter Type Value Notes
URL
object_id string 31944231-fd52-4a7f-b32e-7902a01fddf9 The object ID (GUID) of the target contact.
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/35110b16-360c-4c4a-93b2-03f065fabd93"
}
PUT https://graph.windows.net/myorganization/contacts/31944231-fd52-4a7f-b32e-7902a01fddf9/$links/manager?api-version=1.6

Response

Status Code:204

Content-Type: application/json

Response List

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

Get a contact's direct reports

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

Parameters

Parameter Type Value Notes
URL
object_id string 31944231-fd52-4a7f-b32e-7902a01fddf9 The object ID (GUID) of the target contact.
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/contacts/31944231-fd52-4a7f-b32e-7902a01fddf9/$links/directReports?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/directReports",
  "value": [
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/8c1315ce-bf6f-4e26-b24f-c830606ef41c/Microsoft.DirectoryServices.Contact"
    }
  ]
}

Response List

Status Code Description
200 OK. Indicates success. One or more direct reports are returned.

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

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



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/contacts/{object_id}/$links/directReports?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/contacts/{object_id}/$links/directReports?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/contacts/{object_id}/$links/directReports");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/contacts/{object_id}/$links/directReports?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/contacts/{object_id}/$links/directReports";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}```

``` php
<?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/contacts/{object_id}/$links/directReports');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

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

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>```

``` Python
########### 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/contacts/{object_id}/$links/directReports?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

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

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/contacts/{object_id}/$links/directReports?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/contacts/{object_id}/$links/directReports')

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

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

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



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

puts response.body

Get a contact's group memberships

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

Parameters

Parameter Type Value Notes
URL
object_id string 31944231-fd52-4a7f-b32e-7902a01fddf9 The object ID (GUID) of the target contact.
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/contacts/31944231-fd52-4a7f-b32e-7902a01fddf9/$links/memberOf?api-version=1.6

Response

Status Code:200

Content-Type: application/json

{
  "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryObjects/$links/memberOf",
  "value": [
    {
      "url": "https://graph.windows.net/myorganization/directoryObjects/12345678-b942-47c9-a10e-a4bee353ce60/Microsoft.DirectoryServices.Group"
    }
  ]
}

Response List |Status Code|Description| |-----------|-----------| |200 |OK. Indicates success. One or more groups and/or directory roles are returned.|

Code Samples

using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;

namespace CSHttpClientSample
{
    static class Program
    {
	    static void Main()
        {
            MakeRequest();

            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

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



		   // Specify values for the following required parameters
			queryString["api-version"] = "1.6";
            // Specify values for path parameters (shown as {...})
            var uri = "https://graph.windows.net/myorganization/contacts/{object_id}/$links/memberOf?" + queryString;


            var response = await client.GetAsync(uri);

            if (response.Content != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
            }
        }
    }
}
@ECHO OFF

REM OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
REM Specify values for path parameters (shown as {...}), values for query parameters
curl -v -X GET "https://graph.windows.net/myorganization/contacts/{object_id}/$links/memberOf?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/contacts/{object_id}/$links/memberOf");
		// Specify values for the following required parameters
		builder.setParameter("api-version", "1.6");
		URI uri = builder.build();
		HttpGet request = new HttpGet(uri);
		HttpResponse response = httpclient.execute(request);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			System.out.println(EntityUtils.toString(entity));
		}
	}
	catch (Exception e)
	{
		System.out.println(e.getMessage());
	}
  }
}
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
	$(function() {
		// OAuth2 is required to access this API. For more information visit:
		// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

		var params = {
			// Specify values for the following required parameters
			'api-version': "1.6",
		};
		
		$.ajax({
			// Specify values for path parameters (shown as {...})
			url: 'https://graph.windows.net/myorganization/contacts/{object_id}/$links/memberOf?' + $.param(params),
			type: 'GET',
		})
		.done(function(data) {
			alert("success");
		})
		.fail(function() {
			alert("error");
		});
	});
</script>
</body>
</html>
#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	// OAuth2 is required to access this API. For more information visit:
	// https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks

	// Specify values for path parameters (shown as {...})
    NSString* path = @"https://graph.windows.net/myorganization/contacts/{object_id}/$links/memberOf";
    NSArray* array = @[
                         @"entities=true",
                      ];
    
    NSString* string = [array componentsJoinedByString:@"&"];
    path = [path stringByAppendingFormat:@"?%@", string];
    NSLog(@"%@", path);

    NSMutableURLRequest* _request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    [_request setHTTPMethod:@"GET"];
    
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData* _connectionData = [NSURLConnection sendSynchronousRequest:_request returningResponse:&response error:&error];
    if(nil != error)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSError* error = nil;
        NSMutableDictionary* json = nil;
        
        NSString* dataString = [[NSString alloc] initWithData:_connectionData encoding:NSUTF8StringEncoding];
        NSLog(@"%@", dataString);
        
        if(nil != _connectionData)
        {
            json = [NSJSONSerialization JSONObjectWithData:_connectionData options:NSJSONReadingMutableContainers error:&error];
        }
        
        if (error || !json)
        {
            NSLog(@"Could not parse loaded json with error:%@", error);
        }
        
        NSLog(@"%@", json);
        _connectionData = nil;
    }
    
    [pool drain];
    return 0;
}
<?php

// This sample uses the pecl_http package. (for more information: http://pecl.php.net/package/pecl_http)
require_once 'HTTP/Request2.php';
$headers = array(
);

$query_params = array(
	// Specify values for the following required parameters
	'api-version' => '1.6',
);

$request = new Http_Request2('https://graph.windows.net/myorganization/contacts/{object_id}/$links/memberOf');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setHeader($headers);

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

$url = $request->getUrl();
$url->setQueryVariables($query_params);

try
{
	$response = $request->send();
	
	echo $response->getBody();
}
catch (HttpException $ex)
{
	echo $ex;
}

?>
########### Python 2.7 #############
import httplib, urllib, base64

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

headers = {
}

params = urllib.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = httplib.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/contacts/{object_id}/$links/memberOf?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################

########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64

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

headers = {
}

params = urllib.parse.urlencode({
	# Specify values for the following required parameters
	'api-version': '1.6',
})

try:
	conn = http.client.HTTPSConnection('graph.windows.net')
	# Specify values for path parameters (shown as {...}) and request body if needed
	conn.request("GET", "/myorganization/contacts/{object_id}/$links/memberOf?%s" % params, "", headers)
	response = conn.getresponse()
	data = response.read()
	print(data)
	conn.close()
except Exception as e:
	print("[Errno {0}] {1}".format(e.errno, e.strerror))

####################################
require 'net/http'

uri = URI('https://graph.windows.net/myorganization/contacts/{object_id}/$links/memberOf')

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

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

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



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

puts response.body