Home > Enterprise >  how to access sharepoint folder using graph api
how to access sharepoint folder using graph api

Time:01-11

In my SharePoint site Document Library, I have a folder called OneDriveInventory and I have a few file inside.

I'm trying to access those file but it look like my Uri request is wrong so I would be really appreciated I can get any help or suggestion on how to fix this.

 Invoke-WebRequest -Uri "https://graph.microsoft.com/v1.0/sites/$siteId/drives/$driveId/OneDriveInventory/$($filename)" -Method GET -OutFile $filePath -Headers $headers

CodePudding user response:

I tried to reproduce the same in my environment and got below results:

I have one SharePoint document library in which I created folder named OneDriveInventory and added files like below:

enter image description here

You can make use of below Graph API call to access file in the above folder:

GET https://graph.microsoft.com/v1.0/sites/<siteID>/drives/<driveID>/root:/OneDriveInventory:/children/<filename>

When I ran the above query in Graph Explorer, I got results successfully like below:

enter image description here

To get the same results from PowerShell, I registered one Azure AD application and added API permissions like below:

enter image description here

Now I generated access token using below PowerShell script:

$tenantId = <tenantID>
$applicationId = <appID>
$secret= <secret>
$param = @{
        Uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
        Method = 'Post';
        Body = @{ 
            grant_type = 'client_credentials'; 
            scope = 'https://graph.microsoft.com/.default'; 
            client_id = $applicationId; 
            client_secret = $secret
        }
   }
$result = Invoke-RestMethod @param
$token = $result.access_token

Response:

enter image description here

To access file from folder, I used below PowerShell script:

$siteID = "3b23b598-f5e4-461f-b038-xxxxxx"
$driveID = "xxxxxxxxxxxxxxxxxxx"
$filename = "sridevi.txt"

$headers=@{}
$headers.Add("Content-Type", "text/plain")
$headers.Add("Authorization", "Bearer $token")
$response=Invoke-WebRequest -Uri "https://graph.microsoft.com/v1.0/sites/$siteID/drives/$driveID/root:/OneDriveInventory:/children/$($filename)" -Method GET -OutFile $filePath -Headers $headers

Response:

enter image description here

When I ran $response.Content, I got full response like below:

enter image description here

  • Related