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
- import { HttpClient } from "@microsoft/sp-http";
- export interface IThirdpartyApiProps {
- description: string;
- myhttpclient:HttpClient;
- }
- import * as React from 'react';
- import * as ReactDom from 'react-dom';
- import { Version } from '@microsoft/sp-core-library';
- import {
- BaseClientSideWebPart,
- IPropertyPaneConfiguration,
- PropertyPaneTextField
- } from '@microsoft/sp-webpart-base';
- import * as strings from 'ThirdpartyApiWebPartStrings';
- import ThirdpartyApi from './components/ThirdpartyApi';
- import { IThirdpartyApiProps } from './components/IThirdpartyApiProps';
- export interface IThirdpartyApiWebPartProps {
- description: string;
- }
- export default class ThirdpartyApiWebPart extends BaseClientSideWebPart<IThirdpartyApiWebPartProps> {
- public render(): void {
- const element: React.ReactElement<IThirdpartyApiProps > = React.createElement(
- ThirdpartyApi,
- {
- description: this.properties.description,
- myhttpclient:this.context.httpClient
- }
- );
- ReactDom.render(element, this.domElement);
- }
- protected onDispose(): void {
- ReactDom.unmountComponentAtNode(this.domElement);
- }
- protected get dataVersion(): Version {
- return Version.parse('1.0');
- }
- protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
- return {
- pages: [
- {
- header: {
- description: strings.PropertyPaneDescription
- },
- groups: [
- {
- groupName: strings.BasicGroupName,
- groupFields: [
- PropertyPaneTextField('description', {
- label: strings.DescriptionFieldLabel
- })
- ]
- }
- ]
- }
- ]
- };
- }
- }
- import * as React from 'react';
- import {sp} from '@pnp/sp';
- import { IThirdpartyApiProps } from './IThirdpartyApiProps';
- import { HttpClient, HttpClientResponse } from '@microsoft/sp-http';
- export interface IthirdpartyState {
- ApiOutput?:any[];
- }
- export default class ThirdpartyApi extends React.Component<IThirdpartyApiProps, IthirdpartyState> {
- constructor(props: IThirdpartyApiProps, state: IthirdpartyState) {
- super(props);
- this.state = {
- ApiOutput: []
- };
- }
- /*async PnpfilePermission(id, arrayId, title){
- const list = sp.web.getList(`/sites/site/Lists/List`);
- const item = list.items.getById(3);
- /*
- const folder = sp.web.getFolderByServerRelativePath('Shared%20Documents/some_folder');
- const folderItem = await folder.getItem();
- const file = sp.web.getFileByServerRelativePath('Shared%20Documents/some_file.docx');
- const fileItem = await file.getItem();
- */
- // Break role inheritence for unique permissions
- /* await item.breakRoleInheritance(false); // Method receives params
- // Get user/group proncipal Id
- const { Id: principalId } = await sp.web.currentUser.select('Id').get();
- // Get role definition Id
- const { Id: roleDefId } = await sp.web.roleDefinitions.getByName('Edit').get();
- // Assigning permissions
- await item.roleAssignments.add(principalId, roleDefId);
- console.log(`Done`);
- }*/
- public componentDidMount(){
- var myoutput = [];
- this._getthirdpartyApi()
- .then(response => {
- myoutput.push(response);
- this.setState({ ApiOutput: myoutput });
- });
- }
- private _getthirdpartyApi(): Promise<any> {
- return this.props.myhttpclient
- .get(
- 'https://jsonplaceholder.typicode.com/photos',
- HttpClient.configurations.v1
- )
- .then((response: HttpClientResponse) => {
- return response.json();
- })
- .then(jsonResponse => {
- console.log(jsonResponse);
- return jsonResponse;
- }) as Promise<any>;
- }
- public render(): React.ReactElement<IThirdpartyApiProps> {
- return (
- <div >
- { this.state.ApiOutput[0] && <Bindvalue bindoutput={this.state.ApiOutput[0]} />}
- </div>
- );
- }
- }
- const Bindvalue = (props) => {
- const Bindedcontent = props.bindoutput.map((httpapi,index) =>
- <div key={index}>
- <span>{httpapi.id}</span><br></br>
- <span>{httpapi.title}</span><br></br>
- <span>{httpapi.url}</span><br></br>
- </div>
- );
- return (
- <div>
- {Bindedcontent}
- </div>
- );
- };
- import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';
- private makeRequest(value1: string, value2: string, value3: string): Promise<HttpClientResponse> {
- const postURL = "https://REST-API-URL";
- const body: string = JSON.stringify({
- 'name1': value1,
- 'name2': value2,
- 'name3': value3,
- });
- const requestHeaders: Headers = new Headers();
- requestHeaders.append('Content-type', 'application/json');
- requestHeaders.append('Cache-Control', 'no-cache');
- //For an OAuth token
- requestHeaders.append('Authorization', 'Bearer <TOKEN>');
- //For Basic authentication
- requestHeaders.append('Authorization', 'Basic <CREDENTIALS>');
- const httpClientOptions: IHttpClientOptions = {
- body: body,
- headers: requestHeaders
- };
- console.log("About to make REST API request.");
- return this.context.httpClient.post(
- postURL,
- HttpClient.configurations.v1,
- httpClientOptions)
- .then((response: Response): Promise<HttpClientResponse> => {
- console.log("REST API response received.");
- return response.json();
- });
- }
I hope this helps someone! Happy Coding :)

susam sarkarPosted Jun 10, 2020, 11:39 AM
Post-operation is not working can you please help ..Can not read property 'post
Madhan ThuraiPosted Apr 29, 2020, 5:29 AM
Add catch in the last chain
Akhila GopakumarPosted Apr 29, 2020, 4:56 AM
In get and post , how can we catch any error received ? i.e, if we try to get from web api, and if it returns error how to handle that ?
Madhan ThuraiPosted Apr 19, 2020, 8:51 AM
Check the context
Akhila GopakumarPosted Apr 19, 2020, 7:51 AM
While using post function I am getting error like "Cannot read property 'post' of undefined". get function is working.