Using the SPO Search REST API to create a Webpart showing Recently Modified Documents containing specific keywords
SharePoint Online provides a powerful Search API that allows developers to query against SharePoint’s search index. In this blog post, we will create a custom web part that utilizes the Search API to retrieve and display the most recently modified documents matching specific keywords.
Our tool of choice for developing custom SharePoint Online web parts is the SharePoint Framework (SPFx). We will write our web part in TypeScript and use ReactJS for the front-end. To follow along, ensure you have administrative access to your SharePoint Online and Office 365 environment.
Here’s our roadmap:
- Setup the Development Environment
- Create a New SharePoint Framework Solution
- Develop the Web Part
- Deploy and Test the Web Part
Step 1: Setup the Development Environment
Firstly, we need to setup our development environment. This involves installing Node.js, Yeoman SharePoint generator, and Gulp. You can install these dependencies with the following commands:
npm install -g yo gulp
npm install -g @microsoft/generator-sharepoint
Step 2: Create a New SharePoint Framework Solution
After setting up the environment, navigate to the folder where you want to create the solution and run the following command:
yo @microsoft/sharepoint
When prompted:
- For the solution name, enter “DocumentSearchWebPart”
- Choose “Use the current folder” for where to place the files
- Choose “Y” to allow tenant admin to deploy the solution to all sites immediately
- Choose “N” for unique permissions to access web APIs
- Choose “WebPart” as the component type
- For the web part name, enter “DocumentSearch”
- For the description, enter “A web part that displays recently modified documents based on search keywords”
- For the framework, choose “React”
Step 3: Develop the Web Part
After creating the solution, navigate to the src/webparts/documentSearch/components/DocumentSearch.tsx
file. This is where we’ll write the code to fetch and display documents from the SharePoint Search API.
import * as React from 'react';
import { IDocumentSearchProps } from './IDocumentSearchProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
export interface IDocumentSearchState {
results: any[];
}
export default class DocumentSearch extends React.Component<IDocumentSearchProps, IDocumentSearchState> {
constructor(props: IDocumentSearchProps) {
super(props);
this.state = {
results: []
};
}
public componentDidMount() {
const keywords = 'your-keywords'; // replace this with your keywords
this.props.context.spHttpClient.get(`${this.props.context.pageContext.web.absoluteUrl}/_api/search/query?querytext='FileType:docx+AND+${escape(keywords)}'&sortlist='LastModifiedTime:descending'&rowlimit=10`, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
return response.json();
})
.then((json) => {
this.setState({ results: json.PrimaryQueryResult.RelevantResults.Table.Rows });
});
}
public render(): React.ReactElement<IDocumentSearchProps> {
return (
<div>
{this.state.results.map((result, index) => {
const cells = result.Cells.map((cell) => {
return cell.Value;
});
return (
<div key={index}>
<h3>{cells.Title}</h3>
<p>Last Modified: {new Date(cells.LastModifiedTime).toLocaleString()}</p>
<a href={cells.Path}>Open Document</a>
</div>
);
})}
</div>
);
}
}
Here, we’re making a GET request to the SharePoint Search API, passing our query text and sort order as parameters. The query text includes the file type (docx in this case) and our search keywords, and we’re sorting the results by Last Modified Time in descending order, which will give us the most recently modified documents first. We’re limiting the results to the top 10.
Step 4: Deploy and Test the Web Part
Finally, we will deploy and test our web part.
To bundle the web part, run the following command:
gulp bundle --ship
And to package the solution:
gulp package-solution --ship
These commands create a .sppkg
package in the sharepoint/solution
folder. Upload this package to the SharePoint App Catalog. You can now add the web part to a page by editing the page and clicking the ‘+’ button to add a new web part.
And there you have it, a custom SharePoint Online web part that utilises the SharePoint Search API to display the most recently modified documents that match specific keywords. You can further customise this web part as needed. Happy coding!