How to Call an External API from a SPFx WebPart


SharePoint Framework is gaining popularity, with its adoption being materialized by so many developers for 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 that SPFx provides us with some inbuilt library to access any web service, so the possibilities are endless, as we can interact/integrate SharePoint with any product/technologies which expose data via a 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's first talk about the Rapid API platform. Simply put, Rapid API is a platform that allows developers to host their custom API and made it publicly available to consumers who want 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, we are going to use one such API available.
  • API Main URL - 
  • This has 4 to 5 endpoints to get a different kind of data like, get world stats, get daily reports totals, get data by country etc...
  • The endPoint which we will use -
  • This endpoint will provide us with total COVID 19 stats world data, like total confirmed, recovered, critical, deaths, last change timestamp, list update timestamp. 
Below is just a screenshot of the sample response that 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 the 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 are details of our demo solution which we will be referring to: 
  • solution name - spfx-covid-stats
  • webpart name - covidStats
  • Entry component - CovidStats.tsx
Step - Passing WebPart context to React component
We would need to use a web part context to call an external API using httpClient class available with this object. This class provides us with a  method to make get and post methods to any API.
Open src\webparts\controls\components\ICovidStatsProps.ts 
Modify the code to what's shown below:
  1. import { WebPartContext } from "@microsoft/sp-webpart-base";  
  3. export interface ICovidStatsProps {  
  4.   context: WebPartContext;  
  5. }  
Open src\webparts\controls\CovidStatsWebPart.ts 
Modify render method to pass the context.
  1. public render(): void {  
  2.    const element: React.ReactElement<ICovidStatsProps> = React.createElement(  
  3.      CovidStats,  
  4.      {  
  5.        context: this.context  
  6.      }  
  7.    );  
  9.    ReactDom.render(element, this.domElement);  
  10.  }  
Please note we have just added the line ‘context:this.context’ 
Step - Create a ServiceProvider 
Now let's create a Service Provider class where we will write a method to get data from External API and that will be called inside our component. 
Create a new file at src\ServiceProvider.ts:
  1. import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';  
  2. import { WebPartContext } from '@microsoft/sp-webpart-base';  
  3. import { Constants } from './webparts/Constant';  
  6. export class ServiceProvider {  
  7.     private wpcontext:WebPartContext;  
  8.     public constructor(context: WebPartContext) {  
  9.        this.wpcontext= context;  
  10.       }  
  11.       private httpClientOptionsForGlobal: IHttpClientOptions = {  
  12.         headers: new Headers({  
  13.             "x-rapidapi-host""",  
  14.             "x-rapidapi-key""<REPLACE WHIT WITH YOUR APIKEY>"  
  15.         }),  
  16.         method: "GET",  
  17.         mode: "cors"  
  18.   };  
  19.   public async getTotals() {  
  21.    var response = await this.wpcontext.httpClient  
  22.   .get("", HttpClient.configurations.v1,this.httpClientOptionsForGlobal);  
  23.   console.log(response);  
  24.   var responeJson : any = await response.json();  
  25.   return responeJson;  
  26.   }  
  28. }  
End Point -
API Key - We will get an API key after subscribing to this API here.
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 the webpart).
Create a new file at src\webparts\covidStats\components\Overview.tsx
Below is the code inside of the component:
  1. import * as React from 'react';  
  2. import styles from './CovidStats.module.scss';  
  3. import { ICovidStatsProps } from './ICovidStatsProps';  
  4. import { escape } from '@microsoft/sp-lodash-subset';  
  5. import { WebPartContext } from '@microsoft/sp-webpart-base';  
  6. import {ServiceProvider} from '../../../ServiceProvider';  
  8. export interface IOverViewProps {  
  9.   context:WebPartContext;  
  10. }  

  11. export interface IOverViewState {  
  12.   data:any;    
  13. }  
  15. export default class OverViewStats extends React.Component<IOverViewProps, IOverViewState> {  
  17.   private serviceProvider;  
  19.   public constructor(props: IOverViewProps, state: IOverViewState) {  
  20.     super(props);  
  21.     this.serviceProvider = new ServiceProvider(this.props.context);  
  23.     this.state = {  
  24.       data:{}  
  25.     };  
  27.   }  
  29.   public render(): React.ReactElement<IOverViewProps> {  
  30.        return(  
  31.       <React.Fragment>  
  32.         <h1>Coronavirus Cases Overview:</h1>  
  33.         <h2>Confirmed : {}</h2>  
  34.         <h2>Recovered: {}</h2>  
  35.         <h2>Critical: {}</h2>  
  36.         <h2>Deaths: {}</h2>  
  37.       </React.Fragment>  
  38.     );  
  39.   }  
  41.   public async  componentDidMount(){  
  42.     this.getData();  
  43.   }  
  45.   private getData(){  
  46.     this.serviceProvider.  
  47.     getTotals()   
  48.       .then(  
  49.         (result: any): void => {  
  50.            console.log(result);  
  51.            this.setState({data:result[0]});  
  52.         }  
  53.       )  
  54.       .catch(error => {  
  55.         console.log(error);  
  56.       });  
  57.   }  
  58. }  
Step - Call custom component
Open src\webparts\covidStats\components\CovidStats.tsx 
Modify your code to what's shown below:
  1. import * as React from 'react';  
  2. import styles from './CovidStats.module.scss';  
  3. import { ICovidStatsProps } from './ICovidStatsProps';  
  4. import { escape } from '@microsoft/sp-lodash-subset';  
  5. import Overview from '../components/Overview';  
  7. export default class CovidStats extends React.Component<ICovidStatsProps, {}> {  
  8.   public render(): React.ReactElement<ICovidStatsProps> {  
  9.     return(  
  10.       <React.Fragment>  
  11.         <Overview context={this.props.context}>  
  12.         </Overview>  
  13.       </React.Fragment>  
  14.     );  
  15.   }  
  16. }  
  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's see this web part in the action. Run gulp serve in your node js command prompt root folder.
gulp serve
This will open the local workbench, we don't SharePoint workbench to test this, as we are not interacting with SharePoint. 
Add the COVID stats web part on the page. Once added, you can see the below output. 
Let us conclude with the concepts that have learned in this article:
  • We can call any external API from SPFx web part using the inbuilt HTTP client library
  • Creating a custom react component
  • Calling a custom react component inside another component.
Hope this helps, Happy coding!!