Calling Third Party API in SPFX using @microsoft/sp-http

Introduction 
 
In this blog, you will learn about Calling Third Party API in SPFX using @microsoft/sp-http 
 
Steps 
 
Open a command prompt. Create a directory for SPFx solution.
md spfx-React-ThirdPartyApi
 
Navigate to the above-created directory.
cd spfx-React-ThirdPartyApi
 
Run the Yeoman SharePoint Generator to create the solution.
yo @microsoft/sharepoint
 
Solution Name
 
Hit Enter to have a default name (spfx-React-ThirdPartyApi in this case) or type in any other name for your solution.
Selected choice - Hit Enter
 
Target for the component
 
Here, we can select the target environment where we are planning to deploy the client web part, i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).
Selected choice - SharePoint Online only (latest)
 
Place of files
 
We may choose to use the same folder or create a subfolder for our solution.
Selected choice - Same folder
 
Deployment option
 
Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.
Selected choice - N (install on each site explicitly)
 
Permissions to access web APIs
 
Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.
Selected choice: N (solution contains unique permissions)
 
Type of client-side component to create
 
We can choose to create a client-side web part or an extension. Choose the web part option.
Selected choice - WebPart
 
Web part name
 
Hit Enter to select the default name or type in any other name.
Selected choice - ThirdpartyApi
 
Web part description
 
Hit Enter to select the default description or type in any other value.
 
Framework to use
 
Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.
Selected choice -  React
 
Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.
Once the scaffolding process is completed, lock down the version of project dependencies by running the below command, 
npm shrinkwrap
 
In the command prompt, type below command to open the solution in the code editor of your choice.
 
code .
 
in IThirdpartyApiProps.ts
  1. import { HttpClient } from "@microsoft/sp-http";  
  2. export interface IThirdpartyApiProps {  
  3.   description: string;  
  4.   myhttpclient:HttpClient;  
  5. }  
in ThirdpartyApiWebPart.ts
 
  1. import * as React from 'react';  
  2. import * as ReactDom from 'react-dom';  
  3. import { Version } from '@microsoft/sp-core-library';  
  4. import {  
  5.   BaseClientSideWebPart,  
  6.   IPropertyPaneConfiguration,  
  7.   PropertyPaneTextField  
  8. } from '@microsoft/sp-webpart-base';  
  9.   
  10. import * as strings from 'ThirdpartyApiWebPartStrings';  
  11. import ThirdpartyApi from './components/ThirdpartyApi';  
  12. import { IThirdpartyApiProps } from './components/IThirdpartyApiProps';  
  13.   
  14. export interface IThirdpartyApiWebPartProps {  
  15.   description: string;  
  16. }  
  17.   
  18. export default class ThirdpartyApiWebPart extends BaseClientSideWebPart<IThirdpartyApiWebPartProps> {  
  19.   public render(): void {  
  20.     const element: React.ReactElement<IThirdpartyApiProps > = React.createElement(  
  21.       ThirdpartyApi,  
  22.       {  
  23.         description: this.properties.description,  
  24.         myhttpclient:this.context.httpClient  
  25.       }  
  26.     );  
  27.     ReactDom.render(element, this.domElement);  
  28.   }  
  29.   protected onDispose(): void {  
  30.     ReactDom.unmountComponentAtNode(this.domElement);  
  31.   }  
  32.   protected get dataVersion(): Version {  
  33.     return Version.parse('1.0');  
  34.   }  
  35.   protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {  
  36.     return {  
  37.       pages: [  
  38.         {  
  39.           header: {  
  40.             description: strings.PropertyPaneDescription  
  41.           },  
  42.           groups: [  
  43.             {  
  44.               groupName: strings.BasicGroupName,  
  45.               groupFields: [  
  46.                 PropertyPaneTextField('description', {  
  47.                   label: strings.DescriptionFieldLabel  
  48.                 })  
  49.               ]  
  50.             }  
  51.           ]  
  52.         }  
  53.       ]  
  54.     };  
  55.   }  
  56. }  
 in ThirdpartyApi.tsx
 
  1. import * as React from 'react';  
  2. import {sp} from '@pnp/sp';  
  3. import { IThirdpartyApiProps } from './IThirdpartyApiProps';  
  4. import { HttpClient, HttpClientResponse } from '@microsoft/sp-http';  
  5. export interface IthirdpartyState {    
  6.   ApiOutput?:any[];  
  7. }   
  8. export default class ThirdpartyApi extends React.Component<IThirdpartyApiProps, IthirdpartyState> {  
  9.   constructor(props: IThirdpartyApiProps, state: IthirdpartyState) {  
  10.     super(props);  
  11.     this.state = {  
  12.       ApiOutput: []  
  13.     };  
  14.   }  
  15.     
  16.   /*async  PnpfilePermission(id, arrayId, title){ 
  17.     const list = sp.web.getList(`/sites/site/Lists/List`); 
  18.     const item = list.items.getById(3); 
  19.    
  20.     /* 
  21.     const folder = sp.web.getFolderByServerRelativePath('Shared%20Documents/some_folder'); 
  22.     const folderItem = await folder.getItem(); 
  23.    
  24.     const file = sp.web.getFileByServerRelativePath('Shared%20Documents/some_file.docx'); 
  25.     const fileItem = await file.getItem(); 
  26.     */  
  27.     
  28.     // Break role inheritence for unique permissions  
  29.    /* await item.breakRoleInheritance(false); // Method receives params 
  30.    
  31.     // Get user/group proncipal Id 
  32.     const { Id: principalId } = await sp.web.currentUser.select('Id').get(); 
  33.     // Get role definition Id 
  34.     const { Id: roleDefId } = await sp.web.roleDefinitions.getByName('Edit').get(); 
  35.    
  36.     // Assigning permissions 
  37.     await item.roleAssignments.add(principalId, roleDefId); 
  38.    
  39.     console.log(`Done`); 
  40.      
  41.     }*/  
  42.   public componentDidMount(){  
  43.     var myoutput = [];  
  44.     this._getthirdpartyApi()  
  45.     .then(response => {  
  46.       myoutput.push(response);  
  47.       this.setState({ ApiOutput: myoutput });  
  48.     });  
  49.   }  
  50.   private _getthirdpartyApi(): Promise<any> {  
  51.     return this.props.myhttpclient  
  52.     .get(  
  53.       'https://jsonplaceholder.typicode.com/photos',  
  54.       HttpClient.configurations.v1  
  55.     )  
  56.     .then((response: HttpClientResponse) => {  
  57.       return response.json();  
  58.     })  
  59.     .then(jsonResponse => {  
  60.       console.log(jsonResponse);  
  61.       return jsonResponse;  
  62.     }) as Promise<any>;  
  63.   }   
  64.   public render(): React.ReactElement<IThirdpartyApiProps> {  
  65.     return (  
  66.       <div >  
  67.         { this.state.ApiOutput[0] && <Bindvalue bindoutput={this.state.ApiOutput[0]} />}  
  68.       </div>  
  69.     );  
  70.   }  
  71. }  
  72. const Bindvalue = (props) => {  
  73.   const Bindedcontent = props.bindoutput.map((httpapi,index) =>  
  74.     <div key={index}>  
  75.   <span>{httpapi.id}</span><br></br>  
  76.   <span>{httpapi.title}</span><br></br>  
  77.   <span>{httpapi.url}</span><br></br>  
  78.     </div>  
  79.   );  
  80.   return (  
  81.     <div>  
  82.       {Bindedcontent}  
  83.     </div>  
  84.   );  
  85. };  
HttpClient Example Configuration 
 
  1. import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';  
  2.   
  3. private makeRequest(value1: string, value2: string, value3: string): Promise<HttpClientResponse> {  
  4.   
  5.   const postURL = "https://REST-API-URL";  
  6.   
  7.   const body: string = JSON.stringify({  
  8.     'name1': value1,  
  9.     'name2': value2,  
  10.     'name3': value3,  
  11.   });  
  12.   
  13.   const requestHeaders: Headers = new Headers();  
  14.   requestHeaders.append('Content-type''application/json');  
  15.   requestHeaders.append('Cache-Control''no-cache');  
  16.   //For an OAuth token  
  17.   requestHeaders.append('Authorization''Bearer <TOKEN>');  
  18.   //For Basic authentication  
  19.   requestHeaders.append('Authorization''Basic <CREDENTIALS>');  
  20.   
  21.   const httpClientOptions: IHttpClientOptions = {  
  22.     body: body,  
  23.     headers: requestHeaders  
  24.   };  
  25.   
  26.   console.log("About to make REST API request.");  
  27.   
  28.   return this.context.httpClient.post(  
  29.     postURL,  
  30.     HttpClient.configurations.v1,  
  31.     httpClientOptions)  
  32.     .then((response: Response): Promise<HttpClientResponse> => {  
  33.       console.log("REST API response received.");  
  34.       return response.json();  
  35.     });  
  36. }  
 HttpClient api is provided by Microsoft for Crud operations of 3rd party APIs.
 
I hope this helps someone! Happy Coding :)