연락처에 대한 작업 | Graph API 참조

적용 대상: Graph API | Azure Active Directory

이 항목에서는 Azure AD(Active Directory) Graph API를 사용하여 조직 연락처에 대한 작업을 수행하는 방법을 설명합니다. 일반적으로 조직 연락처는 회사 또는 조직 외부에 있는 사용자를 나타냅니다. 조직 연락처는 O365 Outlook 개인 연락처와 다릅니다. Azure AD Graph API를 사용하여 조직 연락처와 다른 디렉터리 개체 간의 관계(예: 관리자, 부하 직원 및 그룹 멤버 자격)를 읽을 수 있습니다. 조직 연락처를 쓰는 기능은 현재 온-프레미스 디렉터리에서 동기화되지 않은 연락처(dirSyncEnabled 속성이 null 또는 false임)로 제한됩니다. 이러한 연락처의 경우 연락처 자체 또는 해당 관리자 속성을 업데이트하거나 삭제할 수 있습니다. Graph API를 사용하여 조직 연락처를 만들 수는 없습니다. 테넌트에서 조직 연락처를 만드는 방법을 비롯하여 조직 연락처에 대한 자세한 내용은 [Contact]를 참조하세요.

Graph API는 Azure Active Directory에서 사용자, 그룹, 조직 연락처 및 응용 프로그램 같은 디렉터리 개체에 대한 프로그래밍 방식 액세스를 제공하는 REST 기반 API입니다.

중요

Azure AD Graph API 기능은 단일 액세스 토큰으로 단일 끝점을 통해 모두 액세스되는 Outlook, OneDrive, OneNote, Planner 및 Office Graph와 같은 다른 Microsoft 서비스의 API도 포함하는 통합 API인 Microsoft Graph를 통해서도 사용할 수 있습니다.

연락처에 대한 REST 작업 수행

Graph API를 사용하여 조직 연락처에 대한 작업을 수행하려면 연락처 리소스 컬렉션, 특정 연락처, 연락처의 탐색 속성 또는 연락처에 대해 호출할 수 있는 함수 또는 동작을 대상으로 하는 끝점에 지원되는 메서드(GET, POST, PATCH, PUT 또는 DELETE)를 사용하여 HTTP 요청을 보냅니다.

Graph API 요청은 다음과 같은 기본 URL을 사용합니다.

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

중요

Graph API에 전송된 요청은 올바른 형식이어야 하고, Graph API의 올바른 끝점 및 버전을 대상으로 하며, Authorization 헤더에 Azure AD에서 가져온 유효한 액세스 토큰을 전달해야 합니다. Graph API를 사용하여 요청을 만들고 응답을 받는 방법에 대한 자세한 내용은 [Operations Overview]를 참조하세요.

테넌트의 모든 연락처 컬렉션, 개별 연락처 또는 특정 연락처의 탐색 속성 중 대상으로 하는 항목에 따라 {resource_path}를 다르게 지정합니다.

  • /contacts는 연락처 리소스 컬렉션을 대상으로 합니다. 이 리소스 경로를 사용하여 테넌트의 모든 연락처 또는 필터링된 연락처 목록을 읽을 수 있습니다.
  • /contacts/{object_id}는 테넌트의 개별 연락처를 대상으로 합니다. 개체 ID(GUID)로 대상 연락처를 지정합니다. 이 리소스 경로를 사용하여 연락처의 선언된 속성을 가져올 수 있습니다. 온-프레미스 디렉터리에서 동기화되지 않은 연락처의 경우 이 리소스 경로를 사용하여 연락처의 선언된 속성을 수정하거나 연락처를 삭제할 수 있습니다.
  • /contacts/{object_id}/{nav_property}는 연락처의 지정된 탐색 속성을 대상으로 합니다. 이 리소스 경로를 사용하여, 지정된 연락처의 대상 탐색 속성에서 참조하는 개체를 반환할 수 있습니다. 참고: 이 주소 지정 형식은 읽기에만 사용할 수 있습니다.
  • /contacts/{object_id}/$links/{nav_property}는 연락처의 지정된 탐색 속성을 대상으로 합니다. 이 주소 지정 형식을 사용하여 탐색 속성을 읽고 수정하는 작업을 모두 수행할 수 있습니다. 읽을 때 속성에서 참조하는 개체는 응답 본문에서 하나 이상의 링크로 반환됩니다. 온-프레미스 디렉터리에서 동기화되지 않은 연락처의 관리자 탐색 속성만 수정할 수 있습니다. 관리자는 요청 본문에 링크로 지정됩니다.

예를 들어 다음 요청은 지정된 연락처의 관리자에 대한 링크를 반환합니다.

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

연락처에 대한 기본 작업

연락처 리소스 컬렉션 또는 특정 연락처를 대상으로 하여 연락처에 대한 읽기 작업을 수행할 수 있습니다. 특정 연락처를 대상으로 하여, 온-프레미스 디렉터리에서 동기화되지 않은 연락처를 업데이트하고 삭제할 수 있습니다. Graph API는 연락처 만들기를 지원하지 않습니다. 또한 온-프레미스 디렉터리에서 동기화된(dirSyncEnabled 속성이 true임) 연락처의 업데이트 및 삭제도 지원하지 않습니다. 다음 항목에서는 연락처에 대한 기본 작업 수행 방법을 보여 줍니다.


여러 연락처 가져오기

연락처 컬렉션을 가져옵니다. 요청에 OData 쿼리 매개 변수를 추가하여 응답을 필터링, 정렬 및 페이징할 수 있습니다. 자세한 내용은 [Supported Queries, Filters, and Paging Options]을 참조하세요.

성공할 경우 [Contact] 개체 컬렉션을 반환하고, 실패할 경우 응답 본문에 오류 정보가 포함됩니다. 오류에 대한 자세한 내용은 Error Codes and Error Handling를 참조하세요.

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

연락처 하나 가져오기

지정된 연락처를 가져옵니다. 개체 ID(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를 참조하세요.

참고: URL에서 "$links" 세그먼트를 제거하여 링크 대신 [User] 또는 [Contact] 개체를 반환할 수 있습니다.

{
    "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를 참조하세요.

참고: URL에서 "$links" 세그먼트를 제거하여 링크 대신 사용자 및 연락처의 DirectoryObject를 반환할 수 있습니다.

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

연락처의 그룹 멤버 자격 가져오기

memberOf 탐색 속성에서 연락처의 그룹 멤버 자격을 가져옵니다.

이 속성은 연락처가 직접 멤버인 그룹만 반환합니다. 연락처가 직접 멤버 자격 또는 전이적 멤버 자격이 있는 그룹을 모두 가져오려면 [getMemberGroups] 함수를 호출합니다.

성공할 경우 이 연락처가 멤버인 [Group]의 링크 컬렉션을 반환하고, 실패할 경우 응답 본문에 오류 정보가 포함됩니다. 오류에 대한 자세한 내용은 Error Codes and Error Handling를 참조하세요.

참고: URL에서 "$links" 세그먼트를 제거하여 링크 대신 그룹의 DirectoryObject를 반환할 수 있습니다.

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

연락처에 대한 함수 및 동작

연락처에 대해 다음 함수를 호출할 수 있습니다.

특정 그룹의 멤버 자격 확인(전이적)

[isMemberOf] 함수를 호출하여 특정 그룹의 멤버 자격을 확인할 수 있습니다. 확인은 전이적으로 수행됩니다.

그룹 목록의 멤버 자격 확인(전이적)

[checkMemberGroups] 함수를 호출하여 그룹 목록의 멤버 자격을 확인할 수 있습니다. 확인은 전이적으로 수행됩니다.

모든 그룹 멤버 자격 가져오기(전이적)

[getMemberGroups] 함수를 호출하여 연락처가 멤버인 모든 그룹을 반환할 수 있습니다. 확인은 연락처가 직접 멤버인 그룹만 반환하는 memberOf 탐색 속성 읽기와 달리 전이적입니다.


추가 리소스


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