Leverage Microsoft Graph & third-party APIs in SPFx solution

This post is targeted to show a demonstration on how to leverage Microsoft Graph and third-party APIs in our SPFx solution. The intent of this post is to keep the hands-on guidance which can be followed on the same topic as part of Session in M365 Ahmedabad Bootcamp 2020.

Pre-requisite

Create new SPFx solution

Open a command prompt. Create a new directory and navigate.

md react-spfx-api-demo
cd react-spfx-api-demo

Run below command to start creating new SPFx solution

yo @microsoft/sharepoint

Choose the below options when promoted.

Once it is generated, we should see below

Install react-json-view npm package.

For this demo, we will use a simple react-json-view package to view the API response in beautified JSON format.

https://www.npmjs.com/package/react-json-view

npm install --save react-json-view

Open this project in your favorite code editor, mine is Visual Studio Code.

Step – Passing WebPart context to React component

Open “\src\webparts\apiDemo\components\IApiDemoProps.ts”

Modify the code to what’s shown below:

import { WebPartContext } from "@microsoft/sp-webpart-base";

export interface IApiDemoProps {
  description: string;
  context:WebPartContext;
}
Open react-spfx-api-demo\src\webparts\apiDemo\ApiDemoWebPart.ts
Open “src\webparts\apiDemo\components\ApiDemo.tsx”
Modify render method to pass the context.
public render(): void {
    const element: React.ReactElement<IApiDemoProps> = React.createElement(
      ApiDemo,
      {
        description: this.properties.description,
        context:this.context
      }
    );

    ReactDom.render(element, this.domElement);
  }

Please note we have just added the line ‘context:this.context’

Now, Lets Import json-view package.

import ReactJson from 'react-json-view';

Step – Calling External(anonymous) API

In this demo, we will call a public API which will return us all the countries and some particular fields.

https://restcountries.eu/rest/v2/all?fields=name;capital;currencies

As we are using React, let us create required State objects to hold the data for our component.

export interface IApiDemoState {
  countryresponse:any;
}

Now let us make our react component aware of this state.

export default class ApiDemo extends React.Component<IApiDemoProps, IApiDemoState> {

 public constructor(props:IApiDemoProps,state:IApiDemoState){
  super(props);
  this.state = {  
    countryresponse:{}  
  }; 
 }

Add the below link in the render method of the component.

<ReactJson src={this.state.countryresponse} />

Next, let us start to write code to get data from REST API, Add below method

  private async getCountryData(){

    var apiresponse = await this.props.context.httpClient.get(
      `https://restcountries.eu/rest/v2/all?fields=name;capital;currencies`,
      HttpClient.configurations.v1
    )
    .then((response: HttpClientResponse) => {
      return response.json();
    })
    .then(jsonResponse => {
      return jsonResponse;
    }) as Promise<any>;

    this.setState({countryresponse:apiresponse});
    console.log(apiresponse);
  }
}

Now its time to call this method to get data, we will use componentDidMount method to call this method

public componentDidMount(){
   this.getCountryData();

 }

Step  – Test your web part, go to Node JS command prompt, and browse till your project structure.

D:\SP\Samples\react-spfx-api-demo>gulp serve

You should see the below output after running this command…

 

 

Step – Calling Graph API

In this demo, we will call Graph Teams API to get a list of teams of the current users.

End Point – https://docs.microsoft.com/en-us/graph/api/user-list-joinedteams?view=graph-rest-1.0&tabs=http

Open src\webparts\apiDemo\components\ApiDemo.tsx

Import required Library.

import { MSGraphClient } from "@microsoft/sp-http";

Add below method

private async getMyTeams(){
    var _graphClient:MSGraphClient = await this.props.context.msGraphClientFactory.getClient(); //TODO  
  
    
    try {  
      const teamsResponse = await _graphClient.api('me/joinedTeams').version('v1.0').get();  
      myTeams = teamsResponse.value as [];  
      this.setState({teamresponse:teamsResponse});
    } catch (error) {  
      console.log('Unable to get teams', error);  
    }  
    
  }

Add the object to hold graph API Response in stage

export interface IApiDemoState {
  countryresponse:any;
  teamresponse:any;
}

Modify constructor to initialize teamresponse with empty object

public constructor(props:IApiDemoProps,state:IApiDemoState){
 super(props);
 this.state = {  
   countryresponse:{},
   teamresponse:{}
 }; 
}

Modify componentdidMount to call geTeams method

public componentDidMount(){
    this.getCountryData();
    this.getMyTeams();

  }

Modify render method to display response of Graph API to json-viewer

<div>My Teams</div>
      <br/>
      <br/>
      <ReactJson src={this.state.teamresponse} />

Step  – Test your web part, go to Node JS command prompt, and browse till your project structure.

D:\SP\Samples\react-spfx-api-demo>gulp serve

You should see the below output after running this command…

 

Summary – In this post, we have seen how to leverage Graph API and third-party APIs in the SPFx solution.

(Visited 17 times, 1 visits today)