sharepoint-onlineweb-partsspfxsharepoint-search

How do I call the SharePoint Search API for Recent News within a SharePoint Framework webpart?


I am creating a webpart using the SharePoint Framework and I am trying to use the search API to get some recent news articles to create a news carousel.

Here is my code snippet:

  private async _getNewsFeedSearchResults() : Promise<string> {
    let request_url = `https://[mytenant].sharepoint.com/sites/test-site/_api/search/query?querytext='(IsDocument:True)+AND+(FileExtension:aspx)+AND+(PromotedState:2)'`;
    const response = await this.context.spHttpClient.get(request_url, SPHttpClient.configurations.v1);
    return await response.text();
  }

The response I get from SharePoint is:

{"error":{"code":"-1, Microsoft.SharePoint.Client.UnknownError","message":"Unknown Error"}}

I suspect that the problem is in my QueryText:

/_api/search/query?querytext='(IsDocument:True)+AND+(FileExtension:aspx)+AND+(PromotedState:2)'

I also tried

/_api/search/query?QueryText=%27((IsDocument%3ATrue)%20AND%20(FileExtension%3Aaspx)%20AND%20(PromotedState%3A2))%27

and I continue to get the same result.


Solution

  • Your QueryText is fine. You need to specify the OData version headers to v3 as the search API doesn't support v4.

    const response = await this.context.spHttpClient.get(
      request_url,
      SPHttpClient.configurations.v1,
      {
        headers: {
          "odata-version": "3.0",
        },
      }
    );