How to make a POST call to Microsoft Graph in SPFx (using MSGraphClient)?
-
15-01-2021 - |
문제
I have difficulties to find code samples of POST calls, using the MSGraphClient.
The only one I find is using the already deprecated graphHTTPClient ( https://docs.microsoft.com/en-us/sharepoint/dev/spfx/call-microsoft-graph-using-graphhttpclient ):
I wonder what would be the proper way to create an Office 365 Group using the modern MSGraphClient syntax; how do I pass the JSON Request body.
해결책
MSGraphClient
is still in preview and will not work in production tenants as of writing this. Have tested the below the code and it works in Developer tenant.
Add the below import statement:
import { MSGraphClient } from "@microsoft/sp-client-preview";
import { Group } from "@microsoft/microsoft-graph-types";
To create a group, make a POST request to the graph groups endpoint as below:
const graphClient : MSGraphClient = this.context.serviceScope.consume(MSGraphClient.serviceKey)
const group : Group = {
displayName: "Sample test group",
description: "Group description",
groupTypes: [
"Unified"
],
mailEnabled: true,
mailNickname: "TestGroup",
securityEnabled: true
};
graphClient
.api("https://graph.microsoft.com/v1.0/groups/")
.post(group)
.then((groupResponse) => {
console.log(groupResponse);
});
Have added the below npm package:
npm install @microsoft/microsoft-graph-types --save-dev
Reference - Use MS Graph
Github sample - API Scopes
다른 팁
This should help you get started. Here I'm registering a webhook
const graphClient = this.context.serviceScope.consume(MSGraphClient.serviceKey)
const future: Date = new Date(Date.now() + 4320 * 60);
const body: object = {
changeType: "created",
notificationUrl: "mywebhookurl",
resource: "me/messages",
expirationDateTime: future.toISOString(),
clientState: "SecretClientState"
};
await graphClient.api(`subscriptions`).post(body);