Skip to content

Commit 06fbfb6

Browse files
committed
Update MS Graph SPFx guidance
- removed outdated references to deprecated code - updated link to correct page with current guidance - closes SharePoint#2116
1 parent 67e0710 commit 06fbfb6

File tree

2 files changed

+73
-398
lines changed

2 files changed

+73
-398
lines changed
Lines changed: 2 additions & 327 deletions
Original file line numberDiff line numberDiff line change
@@ -1,337 +1,12 @@
11
---
22
title: Tutorial - Use GraphHttpClient to call Microsoft Graph
33
description: Use the GraphHttpClient class to make calls to the Microsoft Graph REST API by using the get(), post(), and fetch() methods.
4-
ms.date: 02/02/2018
4+
ms.date: 01/18/2020
55
ms.prod: sharepoint
66
localization_priority: Priority
77
---
88

99
# Use GraphHttpClient to call Microsoft Graph
1010

1111
> [!IMPORTANT]
12-
> The **GraphHttpClient** has been **deprecated** and should no longer be used. It has been replaced with [MSGraphClient](use-msgraph.md)
13-
14-
Use the **GraphHttpClient** class to make calls to the Microsoft Graph REST API. You can make GET, POST, and PATCH requests by using the **get()**, **post()**, and **fetch()** methods. This article shows how to build a web part that uses **GraphHttpClient**, but you can use **GraphHttpClient** in any SharePoint Framework client code.
15-
16-
## Retrieve Office 365 groups using a GET call
17-
18-
You can use the **get()** method to make a REST call to Microsoft Graph. This example shows you how to retrieve a list of Office 365 groups.
19-
20-
### Create a new web part project
21-
22-
1. Create a new project directory in your favorite ___location.
23-
24-
```
25-
mkdir hellograph-webpart
26-
```
27-
28-
2. Go to the project directory.
29-
30-
```
31-
cd hellograph-webpart
32-
```
33-
34-
3. Create a new web part by running the Yeoman SharePoint generator.
35-
36-
```
37-
yo @microsoft/sharepoint
38-
```
39-
40-
4. When prompted:
41-
42-
* Enter a solution name of **hellograph-webpart**.
43-
* Select **Use the current folder** for where to place the files.
44-
* Enter **y** when prompted if you want to allow the tenant admin to deploy the solution to all sites immediately, without running any feature deployment or adding apps in sites.
45-
* Select **Web Part** as the type of client-side component to create.
46-
* Enter **HelloGraph** as your web part name.
47-
* Enter **Calls the Microsoft Graph Groups API** as the web part description.
48-
* Accept the default **No javascript web framework** as the framework, and select Enter.
49-
50-
![GraphHttpClient values to enter at command line](../images/graphhttpclient-web-part-create.jpg)
51-
52-
5. The Yeoman generator builds the web part. When the scaffolding is finished, open your project folder in your code editor. This article uses Visual Studio Code in the steps and screenshots, but you can use any editor that you prefer.
53-
54-
6. Run the gulp serve command and confirm that it runs in the local workbench correctly.
55-
56-
```
57-
gulp serve
58-
```
59-
60-
### Add a button and placeholder for results
61-
62-
Next, you'll modify the HTML to provide a button to retrieve Office 365 groups. The HTML also needs a placeholder to display the groups.
63-
64-
1. In your code editor, open the **/src/webparts/helloGraph/HelloGraphWebPart.ts** file.
65-
66-
2. Modify the **render()** method so that it contains a button and a **div** where the code lists the Office 365 groups after they are retrieved.
67-
68-
Your code should look like the following TypeScript:
69-
70-
```typescript
71-
public render(): void {
72-
this.domElement.innerHTML = `
73-
<div class="${styles.helloGraph}">
74-
<div class="${styles.container}">
75-
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
76-
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
77-
<span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>
78-
<p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using web parts.</p>
79-
<p class="ms-font-l ms-fontColor-white">${escape(this.properties.description)}</p>
80-
<a href="https://aka.ms/spfx" class="${styles.button}">
81-
<span class="${styles.label}">Learn more</span>
82-
</a>
83-
<p>
84-
<input id="readGroups" type="button" value="Read Groups"/>
85-
</p>
86-
<div id="spTableContainer" ></div>
87-
</div>
88-
</div>
89-
</div>
90-
</div>`;
91-
this.domElement.querySelector('#readGroups').addEventListener('click',() => {this._readGroups();});
92-
}
93-
```
94-
95-
You'll define the **_readGroups()** method later.
96-
97-
3. Define an interface to represent each Office 365 group. Add the following code just before the **HelloGraphWebPart** class but after the imports.
98-
99-
```typescript
100-
export interface IOffice365Group {
101-
// Microsoft Graph has more group properties.
102-
displayName: string;
103-
mail: string;
104-
description: string;
105-
}
106-
```
107-
108-
### Use the GraphHttpClient.get method to retrieve Office 365 groups
109-
110-
Next, you'll call the **GraphHttpClient.get()** method to make a REST call to Microsoft Graph to retrieve a list of Office 365 groups.
111-
112-
1. Import the **GraphHttpClient** class and related types by adding the following import statement near the top of the **HelloGraphWebPart.ts** file.
113-
114-
```typescript
115-
import { GraphHttpClient, HttpClientResponse, IGraphHttpClientOptions } from '@microsoft/sp-http';
116-
```
117-
118-
2. Create the **_readGroups()** method by adding the following code to the **HelloGraphWebPart** class.
119-
120-
```typescript
121-
protected _readGroups(){
122-
// Query for all groups on the tenant using Microsoft Graph.
123-
this.context.graphHttpClient.get(`v1.0/groups?$orderby=displayName`, GraphHttpClient.configurations.v1).then((response: HttpClientResponse) => {
124-
if (response.ok) {
125-
return response.json();
126-
} else {
127-
console.warn(response.statusText);
128-
}
129-
}).then((result: any) => {
130-
// Transfer result values to the group variable
131-
this._renderTable(result.value);
132-
});
133-
}
134-
```
135-
136-
In the previous code, the context property has the GraphHttpClient instance. When you call the **get()** method, a REST call is made to Microsoft Graph that passes the specified URL. In this case, the URL is **v1.0/groups?orderby=displayName**. This issues a GET request, and Microsoft Graph returns all Office 365 groups in the tenant in order by display name.
137-
138-
You can issue any GET request by using this technique and entering the correct URL values. To find the URL values, see the [Microsoft Graph documentation](https://developer.microsoft.com/graph/docs/concepts/overview). For example, you can use the URL specified in the [Groups GET request](https://developer.microsoft.com/graph/docs/api-reference/v1.0/api/group_get) topic to get groups.
139-
140-
The **get()** method returns an **HttpClientResponse**, which you can use to determine whether the call was successful. The returned JSON is in the **result.value**. Because you expect multiple groups to be returned, you pass the value to a **_renderTable()** method, which builds a table of rows for each group.
141-
142-
3. Create a **_renderTable()** method to render the returned groups in a table where each row represents a group. Add the following method to the **HelloGraphWebPart** class.
143-
144-
```typescript
145-
protected _renderTable(items: IOffice365Group[]): void {
146-
let html: string = '';
147-
if (items.length<=0){
148-
html=`<p>There are no groups to list...</p>`;
149-
}
150-
else {
151-
html += `
152-
<table><tr>
153-
<th>Display Name</th>
154-
<th>Mail</th>
155-
<th>Description</th></tr>`;
156-
items.forEach((item: IOffice365Group) => {
157-
html += `
158-
<tr>
159-
<td>${item.displayName}</td>
160-
<td>${item.mail}</td>
161-
<td>${item.description}</td>
162-
</tr>`;
163-
});
164-
html += `</table>`;
165-
}
166-
const tableContainer: Element = this.domElement.querySelector('#spTableContainer');
167-
tableContainer.innerHTML = html;
168-
return;
169-
}
170-
```
171-
172-
### Run the web part to call Microsoft Graph
173-
174-
The code needs to call the **GraphHttpClient** application that runs on SharePoint, so you can't run it on the local workbench. You have to package and deploy it to SharePoint.
175-
176-
1. Use gulp to package your solution.
177-
178-
```
179-
gulp package-solution
180-
```
181-
182-
2. Deploy the solution to your SharePoint tenant:
183-
* Go to your site's app catalog.
184-
* Upload or drag and drop the **hellograph-webpart.sppkg** to the app catalog.
185-
* When prompted, if you trust the **hellograph-webpart-client-side-solution**, select **Make this solution available to all sites in the organization**, and select **Deploy**.
186-
187-
3. Use gulp serve to host the web part.
188-
189-
```
190-
gulp serve --nobrowser
191-
```
192-
193-
4. Add the web part to a webpage, or use the SharePoint Workbench.
194-
195-
You should see the following on your page.
196-
197-
![GraphHttpClient web part showing read groups button and one group listed in a table](../images/graphhttpclient-read-groups-display.jpg)
198-
199-
When you select **Read Groups**, you see a list of all the Office 365 groups on your tenant. If no groups are listed, you'll just see a message that indicates that there were no groups. You will create a new group next.
200-
201-
## Create a new Office 365 group using a POST call
202-
203-
You can issue POST calls to the Microsoft Graph API by using the **GraphHttpClient.post()** method. You'll use the **post()** method to create a new Office 365 group.
204-
205-
206-
### Add a button and placeholder for results
207-
208-
Again, you need to modify the HTML to add a button that creates a new group.
209-
210-
1. In your code editor, open the **/src/webparts/helloGraph/HelloGraphWebPart.ts** file.
211-
212-
2. Modify the **render()** method so that it contains a button and a **div** that indicates whether the creation was successful.
213-
214-
Your code should look like the following TypeScript:
215-
216-
```typescript
217-
public render(): void {
218-
this.domElement.innerHTML = `
219-
<div class="${styles.helloGraph}">
220-
<div class="${styles.container}">
221-
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
222-
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
223-
<span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>
224-
<p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using web parts.</p>
225-
<p class="ms-font-l ms-fontColor-white">${escape(this.properties.description)}</p>
226-
<a href="https://aka.ms/spfx" class="${styles.button}">
227-
<span class="${styles.label}">Learn more</span>
228-
</a>
229-
<p>
230-
<input id="readGroups" type="button" value="Read Groups"/>
231-
<input id="createGroup" type="button" value="Create New Group"/>
232-
</p>
233-
<div id="spCreateGroupResults" ></div>
234-
<div id="spTableContainer" ></div>
235-
</div>
236-
</div>
237-
</div>
238-
</div>`;
239-
this.domElement.querySelector('#createGroup').addEventListener('click',() => {this._createGroup();});
240-
this.domElement.querySelector('#readGroups').addEventListener('click',() => {this._readGroups();});
241-
}
242-
```
243-
244-
3. Add the **_createGroup()** method to call the Microsoft Graph API and create a new group.
245-
246-
```typescript
247-
protected _createGroup(){
248-
// Use Microsoft Graph to create a sample group.
249-
this.context.graphHttpClient.post(`v1.0/groups`,GraphHttpClient.configurations.v1,{
250-
body: JSON.stringify({"description": "Self help community for library",
251-
"displayName": "Library Assist",
252-
"groupTypes": [
253-
"Unified"
254-
],
255-
"mailEnabled": true,
256-
"mailNickname": "library",
257-
"securityEnabled": false
258-
})
259-
}).then((response: HttpClientResponse) => {
260-
const resultContainer: Element = this.domElement.querySelector('#spCreateGroupResults');
261-
if (response.ok) {
262-
resultContainer.innerHTML = `<p>Sample group created</p>`;
263-
} else {
264-
resultContainer.innerHTML = `<p>Could not create group see console for details</p>`;
265-
console.warn(response.status);
266-
}
267-
});
268-
}
269-
```
270-
271-
The previous code creates a simple group by using the code example from the Microsoft Graph [Create group](https://developer.microsoft.com/graph/docs/api-reference/v1.0/api/group_post_groups) article.
272-
273-
The **post()** issues a POST REST API call to the **v1.0/groups** URL. The third parameter is an **IGraphHttpClientOptions** value in which the JSON body is specified to describe the new group. The **HttpClientResponse** is used to determine whether the call was successful, and to display an appropriate result.
274-
275-
You can issue a POST call from the Microsoft Graph documentation by using this pattern and specifying the JSON in the body.
276-
277-
### Run the web part to create a new group
278-
279-
1. Use gulp to package your solution.
280-
281-
```
282-
gulp package-solution
283-
```
284-
285-
2. Deploy the solution to your SharePoint tenant:
286-
* Go to your site's app catalog.
287-
* Upload or drag and drop the **hellograph-webpart.sppkg** to the app catalog.
288-
* Because your solution is already registered, you are prompted as to whether you want to replace it. Select **Replace it**.
289-
* When prompted as to whether you trust the solution, select **Deploy**.
290-
291-
3. Use gulp serve to host the web part.
292-
293-
```
294-
gulp serve --nobrowser
295-
```
296-
297-
4. Add the web part to a webpage, or use the SharePoint Workbench.
298-
299-
You should see the following on your page.
300-
301-
![GraphHttpClient web part with create group button indicating group was created successfully](../images/graphhttpclient-group-created.jpg)
302-
303-
5. When you select **Create New Group**, the code creates a new Office 365 group.
304-
305-
> [!NOTE]
306-
> If you try to create the same group again, the code returns an error because the group already exists. The error is logged to the console, which you can view in the browser's developer mode.
307-
308-
## Update a group using a PATCH call
309-
310-
By now you should understand the pattern. If you need to call a Microsoft Graph REST API, use the **get()** or **post()** methods along with the URL for your request. The last method to show is the **fetch()** method. This method allows you to issue a PATCH request to Microsoft Graph to update a resource.
311-
312-
The following code shows how to call the **fetch()** method to update an existing group.
313-
314-
```typescript
315-
this.context.graphHttpClient.fetch(`v1.0/groups/2dfead70-21e4-4f30-bb2b-94b1bbdefdfa`,GraphHttpClient.configurations.v1,{
316-
method: "PATCH",
317-
body: JSON.stringify(
318-
{
319-
"description": "This is the new description",
320-
"displayName": "testtest"
321-
})
322-
}).then((response: HttpClientResponse) => {
323-
const resultContainer: Element = this.domElement.querySelector('#spUpdateGroupResults');
324-
if (response.ok) {
325-
resultContainer.innerHTML = `<p>Group updated</p>`;
326-
} else {
327-
resultContainer.innerHTML = `<p>Could not update group see console for details</p>`;
328-
console.warn(response.status);
329-
}
330-
});
331-
```
332-
333-
The ID of the group is specified in the URL. Get the ID by using a GET call first. The **method** parameter is set to **PATCH**. The body specifies which group properties to modify.
334-
335-
## See also
336-
337-
- [Overview of the GraphHttpClient class](overview-graphhttpclient.md)
12+
> The **GraphHttpClient** has been **deprecated** and should no longer be used. It has been replaced with [MSGraphClient](use-msgraph.md)

0 commit comments

Comments
 (0)