Using Microsoft Graph API to Search in SharePoint

Here is how to Search in Microsoft 365 and SharePoint content programmatically from your daemon app using Microsoft Graph API

I’ll search SharePoint content here but you can use the same technique to search through other Microsoft 365 services – Exchange, Yammer, Teams etc.
I’ll be using PowerShell but same ideas should work for other platforms/languages – Python, C# etc.

First, your app must authenticate to Microsoft. For this, you need to register your application in Microsoft Azure and generate a secret.

Second, your app must be authorized. For unattended search through SharePoint content – e.g. search on behalf of your app credentials – you need Graph API and SharePoint API application “Sites.Read.All” API permissions configured and consented in your Azure registered app.

Here is the PowerShell code sample (you need to specify tenant id, client id and client secret) :

# Using MS Graph API to Search SharePoint with App Authentication 
# specify tenant id, client id and client secret:
$clientID = ""
$clientSecret = ""
$TenantId = ""

# URI and body for authentication:
$uri = "$tenantId/oauth2/v2.0/token"
$body = @{
client_id = $clientID
client_secret = $clientSecret
scope = ""
grant_type = "client_credentials" 

# Get OAuth 2.0 Token
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token
$headers = @{Authorization = "Bearer $token" }

# Search
$entityTypes = "['driveItem','listItem','list','drive','site']"
$apiUrl = ""
$query = "test*"
$body = @"
"requests": [
"entityTypes": $entityTypes,
"query": {
"queryString": "$query"
"from" : 0,
"size" : 5,
"fields": ["WebUrl","lastModifiedBy","name" ],
"region": "NAM"

$res = Invoke-RestMethod -Headers $Headers -Uri $apiUrl -Body $Body -Method Post -ContentType 'application/json'