Search code examples
c#.netsharepointmicrosoft-graph-api

Sharepoint REST API 'search' equivalent in Graph API (.NET)


I am trying to find a way how to call Graph API with fulltext search similar to following query:

https://[tenant].sharepoint.com/sites/[site name/ID]/_api/search/query?queryText='([term to search]*)'

Basically to simulate the seach on Sharepoint site header and thus far I was not able to replicate it in the Graph API.

Note: I tried to work with Pages in /beta, but that do not allow search at the moment.


Solution

  • You can search on a specific SharePoint site by specifying path in queryString.

    API looks like this

    POST https://graph.microsoft.com/v1.0/search/query
    {
        "requests": [
            {
                "entityTypes": [
                    "listItem"
                ],
                "query": {
                    "queryString": "path:\"https://tenant.sharepoint.com/sites/{site_name}\" Test"
                },
                "from": 0,
                "size": 25
            }
        ]
    }
    

    If you are using Microsoft Graph .NET Client Library the code will be

    GraphServiceClient graphClient = new GraphServiceClient( authProvider );
    
    var requests = new List<SearchRequestObject>()
    {
        new SearchRequestObject
        {
            EntityTypes = new List<EntityType>()
            {
                EntityType.ListItem
            },
            Query = new SearchQuery
            {
                QueryString = "path:\"https://tenant.sharepoint.com/sites/{site_name}\" Test"
            },
            From = 0,
            Size = 25
        }
    };
    
    await graphClient.Search
        .Query(requests)
        .Request()
        .PostAsync();
    

    Resources:

    Search API