Пространство имен: microsoft.graph
Важно!
API версии /beta в Microsoft Graph могут быть изменены. Использование этих API в производственных приложениях не поддерживается. Чтобы определить, доступен ли API в версии 1.0, используйте селектор версий.
Отправка приглашения на общий доступ для элемента driveItem. Приглашение на общий доступ предоставляет разрешения получателям и при необходимости отправляет им сообщение электронной почты с уведомлением о том, что элемент был предоставлен.
Важно!
- Разрешения не могут быть созданы или изменены на корневом узле driveItemдисков с типом driveType
personal (OneDrive для дома).
-
Новые гости не могут быть приглашены с доступом только для приложений. Существующих гостей можно пригласить с помощью запросов только для приложений.
Этот API доступен в следующих национальных облачных развертываниях.
| Глобальная служба |
Правительство США L4 |
Правительство США L5 (DOD) |
Китай управляется 21Vianet |
| ✅ |
✅ |
✅ |
✅ |
Разрешения
Выберите разрешение или разрешения, помеченные как наименее привилегированные для этого API. Используйте более привилегированное разрешение или разрешения только в том случае, если это требуется приложению. Дополнительные сведения о делегированных разрешениях и разрешениях приложений см. в разделе Типы разрешений. Дополнительные сведения об этих разрешениях см. в справочнике по разрешениям.
| Тип разрешения |
Разрешения с наименьшими привилегиями |
Более высокие привилегированные разрешения |
| Делегированные (рабочая или учебная учетная запись) |
Files.ReadWrite |
Files.ReadWrite.All, Sites.ReadWrite.All |
| Делегированные (личная учетная запись Майкрософт) |
Files.ReadWrite |
Files.ReadWrite.All |
| Приложение |
Files.ReadWrite.All |
Sites.ReadWrite.All |
HTTP-запрос
POST /drives/{drive-id}/items/{item-id}/invite
POST /groups/{group-id}/drive/items/{item-id}/invite
POST /me/drive/items/{item-id}/invite
POST /sites/{siteId}/drive/items/{itemId}/invite
POST /users/{userId}/drive/items/{itemId}/invite
Текст запроса
В тексте запроса предоставьте JSON-объект с указанными ниже параметрами.
{
"requireSignIn": false,
"sendInvitation": false,
"roles": [ "read | write"],
"recipients": [
{ "@odata.type": "microsoft.graph.driveRecipient" },
{ "@odata.type": "microsoft.graph.driveRecipient" }
],
"message": "string"
}
| Параметр |
Тип |
Описание |
| recipients |
коллекция driveRecipient |
Коллекция получателей, получающих доступ и приглашение общего доступа. |
| message |
String |
Сообщение с обычным форматированным текстом, включенное в приглашение на доступ. Максимальная длина 2000 символов. |
| requireSignIn |
Boolean |
Указывает, куда должен зайти получатель приглашения, чтобы просмотреть элемент, к которому предоставлен общий доступ. |
| sendInvitation |
Boolean |
Указывает, создается ли сообщение электронной почты или публикация (false) или разрешение было создано недавно (true). |
| roles |
Набор строк |
Указывает роли, предоставляемые получателям приглашения на общий доступ. |
| expirationDateTime |
DateTimeOffset |
Указывает дату и время, по истечении которого истекает срок действия разрешения. Для OneDrive для работы или учебного заведения и SharePoint expirationDateTime применяется только для разрешений sharingLink . Доступно в OneDrive для рабочих или учебных учетных записей, SharePoint и личных учетных записей OneDrive уровня "Премиум". |
| password |
Строка |
Пароль, заданный в приглашении создателем. Необязательный параметр и OneDrive только для дома. |
| retainInheritedPermissions |
Boolean |
Необязательное свойство. Если true (по умолчанию) все существующие унаследованные разрешения сохраняются для общего элемента при первом предоставлении общего доступа к этому элементу. Если falseзадано значение , все существующие разрешения удаляются при первом предоставлении общего доступа. |
Отклик
В случае успешного 200 OK выполнения этот метод возвращает код отклика и коллекцию объектов разрешений в тексте ответа.
Дополнительные сведения о том, как возвращаются ошибки, см. в разделе Ответы на ошибки.
Частичный ответ на успех
При приглашении нескольких получателей уведомление может быть успешным для одних и сбоем для других. В этом случае служба возвращает частичный ответ на успешное 207 Multi-Status выполнение с кодом состояния. Если возвращается частичный успех, ответ для каждого неудавшихся получателей содержит объект ошибки с информацией о том, что пошло не так и как ее исправить. Дополнительные сведения см. в разделе Пример 2.
Ошибки отправки уведомлений о приглашении
В следующей таблице показаны некоторые другие ошибки, с которыми приложение может столкнуться во вложенных объектах innererror при сбое отправки уведомления. Приложения не требуются для обработки этих ошибок.
| Код |
Описание |
| accountVerificationRequired |
Чтобы разблокировать отправку уведомлений, требуется проверка учетной записи. |
| hipCheckRequired |
Необходимо решить проверка hip (защита от вторжений узла), чтобы разблокировать отправку уведомлений. |
| exchangeInvalidUser |
Почтовый ящик текущего пользователя не найден. |
| exchangeOutOfMailboxQuota |
Превышена квота. |
| exchangeMaxRecipients |
Превышено максимальное число получателей, которым можно одновременно отправлять уведомления. |
Заметка: Служба может добавить новые коды ошибок или прекратить возврат старых в любое время.
Примеры
Пример 1. Отправка приглашения на общий доступ
В следующем примере показано, как отправить пользователю приглашение на общий доступ с помощью адреса robin@contoso.orgэлектронной почты, включая сообщение о файле в рамках совместной работы. Приглашение предоставляет robin доступ на чтение и запись к файлу.
Запрос
Ниже показан пример запроса.
POST https://graph.microsoft.com/beta/me/drive/items/{item-id}/invite
Content-type: application/json
{
"recipients": [
{
"email": "robin@contoso.org"
}
],
"message": "Here's the file that we're collaborating on.",
"requireSignIn": true,
"sendInvitation": true,
"roles": [ "write" ],
"password": "password123",
"expirationDateTime": "2018-07-15T14:00:00.000Z"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Drives.Item.Items.Item.Invite;
using Microsoft.Graph.Beta.Models;
var requestBody = new InvitePostRequestBody
{
Recipients = new List<DriveRecipient>
{
new DriveRecipient
{
Email = "robin@contoso.org",
},
},
Message = "Here's the file that we're collaborating on.",
RequireSignIn = true,
SendInvitation = true,
Roles = new List<string>
{
"write",
},
Password = "password123",
ExpirationDateTime = "2018-07-15T14:00:00.000Z",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Drives["{drive-id}"].Items["{driveItem-id}"].Invite.PostAsInvitePostResponseAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphdrives "github.com/microsoftgraph/msgraph-beta-sdk-go/drives"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphdrives.NewInvitePostRequestBody()
driveRecipient := graphmodels.NewDriveRecipient()
email := "robin@contoso.org"
driveRecipient.SetEmail(&email)
recipients := []graphmodels.DriveRecipientable {
driveRecipient,
}
requestBody.SetRecipients(recipients)
message := "Here's the file that we're collaborating on."
requestBody.SetMessage(&message)
requireSignIn := true
requestBody.SetRequireSignIn(&requireSignIn)
sendInvitation := true
requestBody.SetSendInvitation(&sendInvitation)
roles := []string {
"write",
}
requestBody.SetRoles(roles)
password := "password123"
requestBody.SetPassword(&password)
expirationDateTime := "2018-07-15T14:00:00.000Z"
requestBody.SetExpirationDateTime(&expirationDateTime)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
invite, err := graphClient.Drives().ByDriveId("drive-id").Items().ByDriveItemId("driveItem-id").Invite().PostAsInvitePostResponse(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.beta.drives.item.items.item.invite.InvitePostRequestBody invitePostRequestBody = new com.microsoft.graph.beta.drives.item.items.item.invite.InvitePostRequestBody();
LinkedList<DriveRecipient> recipients = new LinkedList<DriveRecipient>();
DriveRecipient driveRecipient = new DriveRecipient();
driveRecipient.setEmail("robin@contoso.org");
recipients.add(driveRecipient);
invitePostRequestBody.setRecipients(recipients);
invitePostRequestBody.setMessage("Here's the file that we're collaborating on.");
invitePostRequestBody.setRequireSignIn(true);
invitePostRequestBody.setSendInvitation(true);
LinkedList<String> roles = new LinkedList<String>();
roles.add("write");
invitePostRequestBody.setRoles(roles);
invitePostRequestBody.setPassword("password123");
invitePostRequestBody.setExpirationDateTime("2018-07-15T14:00:00.000Z");
var result = graphClient.drives().byDriveId("{drive-id}").items().byDriveItemId("{driveItem-id}").invite().post(invitePostRequestBody);
const options = {
authProvider,
};
const client = Client.init(options);
const permission = {
recipients: [
{
email: 'robin@contoso.org'
}
],
message: 'Here\'s the file that we\'re collaborating on.',
requireSignIn: true,
sendInvitation: true,
roles: [ 'write' ],
password: 'password123',
expirationDateTime: '2018-07-15T14:00:00.000Z'
};
await client.api('/me/drive/items/{item-id}/invite')
.version('beta')
.post(permission);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Drives\Item\Items\Item\Invite\InvitePostRequestBody;
use Microsoft\Graph\Beta\Generated\Models\DriveRecipient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new InvitePostRequestBody();
$recipientsDriveRecipient1 = new DriveRecipient();
$recipientsDriveRecipient1->setEmail('robin@contoso.org');
$recipientsArray []= $recipientsDriveRecipient1;
$requestBody->setRecipients($recipientsArray);
$requestBody->setMessage('Here\'s the file that we\'re collaborating on.');
$requestBody->setRequireSignIn(true);
$requestBody->setSendInvitation(true);
$requestBody->setRoles(['write', ]);
$requestBody->setPassword('password123');
$requestBody->setExpirationDateTime('2018-07-15T14:00:00.000Z');
$result = $graphServiceClient->drives()->byDriveId('drive-id')->items()->byDriveItemId('driveItem-id')->invite()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Files
$params = @{
recipients = @(
@{
email = "robin@contoso.org"
}
)
message = "Here's the file that we're collaborating on."
requireSignIn = $true
sendInvitation = $true
roles = @(
"write"
)
password = "password123"
expirationDateTime = "2018-07-15T14:00:00.000Z"
}
Invoke-MgBetaInviteDriveItem -DriveId $driveId -DriveItemId $driveItemId -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.drives.item.items.item.invite.invite_post_request_body import InvitePostRequestBody
from msgraph_beta.generated.models.drive_recipient import DriveRecipient
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = InvitePostRequestBody(
recipients = [
DriveRecipient(
email = "robin@contoso.org",
),
],
message = "Here's the file that we're collaborating on.",
require_sign_in = True,
send_invitation = True,
roles = [
"write",
],
password = "password123",
expiration_date_time = "2018-07-15T14:00:00.000Z",
)
result = await graph_client.drives.by_drive_id('drive-id').items.by_drive_item_id('driveItem-id').invite.post(request_body)
Отклик
Ниже показан пример отклика.
HTTP/1.1 200 OK
Content-type: application/json
{
"value": [
{
"@deprecated.GrantedTo": "GrantedTo has been deprecated. Refer to GrantedToV2",
"grantedTo": {
"user": {
"displayName": "Robin Danielsen",
"id": "42F177F1-22C0-4BE3-900D-4507125C5C20"
}
},
"grantedToV2": {
"user": {
"id": "42F177F1-22C0-4BE3-900D-4507125C5C20",
"displayName": "Robin Danielsen"
},
"siteUser": {
"id": "1",
"displayName": "Robin Danielsen",
"loginName": "Robin Danielsen"
}
},
"hasPassword": true,
"id": "CCFC7CA3-7A19-4D57-8CEF-149DB9DDFA62",
"invitation": {
"email": "robin@contoso.com",
"signInRequired": true
},
"roles": [ "write" ],
"expirationDateTime": "2018-07-15T14:00:00.000Z"
}
]
}
Пример 2. Отправка приглашения на общий доступ с частичным успехом
В следующем примере показан частично успешный запрос.
Запрос
Ниже показан пример запроса.
POST https://graph.microsoft.com/beta/me/drive/items/{item-id}/invite
Content-type: application/json
{
"recipients": [
{
"email": "helga@contoso.com"
},
{
"email": "robin@contoso.org"
}
],
"message": "Here's the file that we're collaborating on.",
"requireSignIn": true,
"sendInvitation": true,
"roles": [ "write" ],
"password": "password123",
"expirationDateTime": "2018-07-15T14:00:00.000Z"
}
// Code snippets are only available for the latest version. Current version is 5.x
// Dependencies
using Microsoft.Graph.Beta.Drives.Item.Items.Item.Invite;
using Microsoft.Graph.Beta.Models;
var requestBody = new InvitePostRequestBody
{
Recipients = new List<DriveRecipient>
{
new DriveRecipient
{
Email = "helga@contoso.com",
},
new DriveRecipient
{
Email = "robin@contoso.org",
},
},
Message = "Here's the file that we're collaborating on.",
RequireSignIn = true,
SendInvitation = true,
Roles = new List<string>
{
"write",
},
Password = "password123",
ExpirationDateTime = "2018-07-15T14:00:00.000Z",
};
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
var result = await graphClient.Drives["{drive-id}"].Items["{driveItem-id}"].Invite.PostAsInvitePostResponseAsync(requestBody);
// Code snippets are only available for the latest major version. Current major version is $v0.*
// Dependencies
import (
"context"
msgraphsdk "github.com/microsoftgraph/msgraph-beta-sdk-go"
graphdrives "github.com/microsoftgraph/msgraph-beta-sdk-go/drives"
graphmodels "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
//other-imports
)
requestBody := graphdrives.NewInvitePostRequestBody()
driveRecipient := graphmodels.NewDriveRecipient()
email := "helga@contoso.com"
driveRecipient.SetEmail(&email)
driveRecipient1 := graphmodels.NewDriveRecipient()
email := "robin@contoso.org"
driveRecipient1.SetEmail(&email)
recipients := []graphmodels.DriveRecipientable {
driveRecipient,
driveRecipient1,
}
requestBody.SetRecipients(recipients)
message := "Here's the file that we're collaborating on."
requestBody.SetMessage(&message)
requireSignIn := true
requestBody.SetRequireSignIn(&requireSignIn)
sendInvitation := true
requestBody.SetSendInvitation(&sendInvitation)
roles := []string {
"write",
}
requestBody.SetRoles(roles)
password := "password123"
requestBody.SetPassword(&password)
expirationDateTime := "2018-07-15T14:00:00.000Z"
requestBody.SetExpirationDateTime(&expirationDateTime)
// To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=go
invite, err := graphClient.Drives().ByDriveId("drive-id").Items().ByDriveItemId("driveItem-id").Invite().PostAsInvitePostResponse(context.Background(), requestBody, nil)
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
com.microsoft.graph.beta.drives.item.items.item.invite.InvitePostRequestBody invitePostRequestBody = new com.microsoft.graph.beta.drives.item.items.item.invite.InvitePostRequestBody();
LinkedList<DriveRecipient> recipients = new LinkedList<DriveRecipient>();
DriveRecipient driveRecipient = new DriveRecipient();
driveRecipient.setEmail("helga@contoso.com");
recipients.add(driveRecipient);
DriveRecipient driveRecipient1 = new DriveRecipient();
driveRecipient1.setEmail("robin@contoso.org");
recipients.add(driveRecipient1);
invitePostRequestBody.setRecipients(recipients);
invitePostRequestBody.setMessage("Here's the file that we're collaborating on.");
invitePostRequestBody.setRequireSignIn(true);
invitePostRequestBody.setSendInvitation(true);
LinkedList<String> roles = new LinkedList<String>();
roles.add("write");
invitePostRequestBody.setRoles(roles);
invitePostRequestBody.setPassword("password123");
invitePostRequestBody.setExpirationDateTime("2018-07-15T14:00:00.000Z");
var result = graphClient.drives().byDriveId("{drive-id}").items().byDriveItemId("{driveItem-id}").invite().post(invitePostRequestBody);
const options = {
authProvider,
};
const client = Client.init(options);
const permission = {
recipients: [
{
email: 'helga@contoso.com'
},
{
email: 'robin@contoso.org'
}
],
message: 'Here\'s the file that we\'re collaborating on.',
requireSignIn: true,
sendInvitation: true,
roles: [ 'write' ],
password: 'password123',
expirationDateTime: '2018-07-15T14:00:00.000Z'
};
await client.api('/me/drive/items/{item-id}/invite')
.version('beta')
.post(permission);
<?php
use Microsoft\Graph\Beta\GraphServiceClient;
use Microsoft\Graph\Beta\Generated\Drives\Item\Items\Item\Invite\InvitePostRequestBody;
use Microsoft\Graph\Beta\Generated\Models\DriveRecipient;
$graphServiceClient = new GraphServiceClient($tokenRequestContext, $scopes);
$requestBody = new InvitePostRequestBody();
$recipientsDriveRecipient1 = new DriveRecipient();
$recipientsDriveRecipient1->setEmail('helga@contoso.com');
$recipientsArray []= $recipientsDriveRecipient1;
$recipientsDriveRecipient2 = new DriveRecipient();
$recipientsDriveRecipient2->setEmail('robin@contoso.org');
$recipientsArray []= $recipientsDriveRecipient2;
$requestBody->setRecipients($recipientsArray);
$requestBody->setMessage('Here\'s the file that we\'re collaborating on.');
$requestBody->setRequireSignIn(true);
$requestBody->setSendInvitation(true);
$requestBody->setRoles(['write', ]);
$requestBody->setPassword('password123');
$requestBody->setExpirationDateTime('2018-07-15T14:00:00.000Z');
$result = $graphServiceClient->drives()->byDriveId('drive-id')->items()->byDriveItemId('driveItem-id')->invite()->post($requestBody)->wait();
Import-Module Microsoft.Graph.Beta.Files
$params = @{
recipients = @(
@{
email = "helga@contoso.com"
}
@{
email = "robin@contoso.org"
}
)
message = "Here's the file that we're collaborating on."
requireSignIn = $true
sendInvitation = $true
roles = @(
"write"
)
password = "password123"
expirationDateTime = "2018-07-15T14:00:00.000Z"
}
Invoke-MgBetaInviteDriveItem -DriveId $driveId -DriveItemId $driveItemId -BodyParameter $params
# Code snippets are only available for the latest version. Current version is 1.x
from msgraph_beta import GraphServiceClient
from msgraph_beta.generated.drives.item.items.item.invite.invite_post_request_body import InvitePostRequestBody
from msgraph_beta.generated.models.drive_recipient import DriveRecipient
# To initialize your graph_client, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=python
request_body = InvitePostRequestBody(
recipients = [
DriveRecipient(
email = "helga@contoso.com",
),
DriveRecipient(
email = "robin@contoso.org",
),
],
message = "Here's the file that we're collaborating on.",
require_sign_in = True,
send_invitation = True,
roles = [
"write",
],
password = "password123",
expiration_date_time = "2018-07-15T14:00:00.000Z",
)
result = await graph_client.drives.by_drive_id('drive-id').items.by_drive_item_id('driveItem-id').invite.post(request_body)
Отклик
В следующем примере показан частичный ответ.
HTTP/1.1 207 Multi-Status
Content-type: application/json
{
"value": [
{
"grantedTo": {
"user": {
"displayName": "Helga Hammeren",
"id": "5D8CA5D0-FFF8-4A97-B0A6-8F5AEA339681"
}
},
"id": "1EFG7CA3-7A19-4D57-8CEF-149DB9DDFA62",
"invitation": {
"email": "helga@contoso.com",
"signInRequired": true
},
"roles": [ "write" ],
"error": {
"code":"notAllowed",
"message":"Account verification needed to unblock sending emails.",
"localizedMessage": "Kontobestätigung erforderlich, um das Senden von E-Mails zu entsperren.",
"fixItUrl":"http://g.live.com/8SESkydrive/VerifyAccount",
"innererror":{
"code":"accountVerificationRequired"
}
}
},
{
"grantedTo": {
"user": {
"displayName": "Robin Danielsen",
"id": "42F177F1-22C0-4BE3-900D-4507125C5C20"
}
},
"id": "CCFC7CA3-7A19-4D57-8CEF-149DB9DDFA62",
"invitation": {
"email": "robin@contoso.com",
"signInRequired": true
},
"roles": [ "write" ],
"expirationDateTime": "2018-07-15T14:00:00.000Z"
}
]
}
Связанные материалы
Список доступных ролей см. в разделе Значения свойств ролей.