How to call an External API from SPFx webpart

SharePoint Framework is gaining its popularity with its adoption being materialized by so many developers for doing client-side customization in SharePoint. In this article, we will learn how to call an External API and get non-SharePoint based data to display in SPFx web part. We have to understand here is that SPFx provides us with some inbuilt library to access any web service, so possibilities are endless as we can interact/integrate SharePoint with any product/technologies which exposes its data via web service or API.
Today we are going to call one simple API web service to get COVID 19 stats data which is publicly available via the RAPID API platform. Before we move ahead let us first talk about Rapid API platform. In simple form, Rapid API is a platform which allows developers to host their custom API and made it publicly available to consumer those who wants to use it. Basically it is the API marketplace. Many of the API hosted are either free, freemium, or premium based subscription which we can use. It provides a single SDK to access multiple API endpoints by different developers/companies. You can read more at this link.
For our demo purpose, we are going to use one such API available.
Below is just a screenshot of the sample response which we will get.

We need to subscribe to the above API and it will provide us with API Key, we will need this key in our code to call API.
So now let us jump to SPFx part. Assuming you know how to create a simple React SPFx web part. If you are first-timer, you can follow this article to get an idea of how create a react based web part. Please note that you can do this in No javascript framework or vue.js.
In our example, below is details of our demo solution which we we wil be referring.
  • solution name – spfx-covid-stats
  • webpart name –  covidStats
  • Entry component –  CovidStats.tsx

Step – Passing WebPart context to React component

We would need to use webpart context to call external API using httpClient class available with this object. this class provides us method to make get and post method to any API.

Open src\webparts\controls\components\ICovidStatsProps.ts

Modify code to below

import { WebPartContext } from "@microsoft/sp-webpart-base";  
  
export interface ICovidStatsProps {  
  context: WebPartContext;  
}

Open src\webparts\controls\CovidStatsWebPart.ts

Modify render method to pass the context.

public render(): void {  
   const element: React.ReactElement<ICovidStatsProps> = React.createElement(  
     CovidStats,  
     {  
       context: this.context  
     }  
   );  
  
   ReactDom.render(element, this.domElement);  
 }

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

Step – Create a ServiceProvider 
Now let us create a Service Provider class where we will write a method to get data from External API and which will be called inside our component.
Create new file at src\ServiceProvider.ts
import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';  
import { WebPartContext } from '@microsoft/sp-webpart-base';  
import { Constants } from './webparts/Constant';  
  
  
export class ServiceProvider {  
    private wpcontext:WebPartContext;  
    public constructor(context: WebPartContext) {  
       this.wpcontext= context;  
      }  
      private httpClientOptionsForGlobal: IHttpClientOptions = {  
        headers: new Headers({  
            "x-rapidapi-host": "covid-19-data.p.rapidapi.com",  
            "x-rapidapi-key": "<REPLACE WHIT WITH YOUR APIKEY>"  
        }),  
        method: "GET",  
        mode: "cors"  
  };  
  public async getTotals() {  
  
   var response = await this.wpcontext.httpClient  
  .get("https://covid-19-data.p.rapidapi.com/totals", HttpClient.configurations.v1,this.httpClientOptionsForGlobal);  
  console.log(response);  
  var responeJson : any = await response.json();  
  return responeJson;  
  }  
    
}
Step – Create a custom component
For this example, we will explore one more concept of creating a custom react component and calling it from our yeoman generated component(entry point to webpart).
Create new file at src\webparts\covidStats\components\Overview.tsx
Below should be code inside component
import * as React from 'react';  
import styles from './CovidStats.module.scss';  
import { ICovidStatsProps } from './ICovidStatsProps';  
import { escape } from '@microsoft/sp-lodash-subset';  
import { WebPartContext } from '@microsoft/sp-webpart-base';  
import {ServiceProvider} from '../../../ServiceProvider';  
  
export interface IOverViewProps {  
  context:WebPartContext;  
}  

export interface IOverViewState {  
  data:any;    
}  
  
export default class OverViewStats extends React.Component<IOverViewProps, IOverViewState> {  
  
  private serviceProvider;  
  
  public constructor(props: IOverViewProps, state: IOverViewState) {  
    super(props);  
    this.serviceProvider = new ServiceProvider(this.props.context);  
  
    this.state = {  
      data:{}  
    };  
  
  }  
  
  public render(): React.ReactElement<IOverViewProps> {  
       return(  
      <React.Fragment>  
        <h1>Coronavirus Cases Overview:</h1>  
        <h2>Confirmed : {this.state.data.confirmed}</h2>  
        <h2>Recovered: {this.state.data.recovered}</h2>  
        <h2>Critical: {this.state.data.critical}</h2>  
        <h2>Deaths: {this.state.data.deaths}</h2>  
      </React.Fragment>  
    );  
  }  
  
  public async  componentDidMount(){  
    this.getData();  
  }  
  
  private getData(){  
    this.serviceProvider.  
    getTotals()   
      .then(  
        (result: any): void => {  
           console.log(result);  
           this.setState({data:result[0]});  
        }  
      )  
      .catch(error => {  
        console.log(error);  
      });  
  }  
}

Step – Call custom component

Open src\webparts\covidStats\components\CovidStats.tsx

Modify your code to below

import * as React from 'react';  
import styles from './CovidStats.module.scss';  
import { ICovidStatsProps } from './ICovidStatsProps';  
import { escape } from '@microsoft/sp-lodash-subset';  
import Overview from '../components/Overview';  
  
export default class CovidStats extends React.Component<ICovidStatsProps, {}> {  
  public render(): React.ReactElement<ICovidStatsProps> {  
    return(  
      <React.Fragment>  
        <Overview context={this.props.context}>  
        </Overview>  
      </React.Fragment>  
    );  
  }  
}
Notes
1. We have imported our custom created comoponent at line 5
2. Removed yoeman generated html and replace with our by calling our custom component Overview at line 10 to 13.
Now let us see this web part in the action. Run gulp serve in your node js command prompt root folder.
gulp serve
This will open local workbench, we don’t SharePoint workbench to test this as we are not interacting with SharePoint.
Add covid stats web part on-page, and once added you can see below output.

Let us conclude concepts we have learned in this article
  • We can call any external API from SPFx web part using the inbuilt HTTP client library
  • Creating custom react component
  • Calling custom react component inside another component.
Hope this helps, Happy coding..!!
P.S – This article was originally published at this link
(Visited 42 times, 1 visits today)