We can use Microsoft Graph API to connect and work with files in OneDrive for Business and SharePoint Online document libraries. Microsoft Graph exposes the following two resource types to represent List (Library) and List Items (files).
- Drive – Represents a logical container of files (List or Document library).
- DriveItem – Represents a file, folder, or other item (List Item) stored in a drive.
Consider that you have a file in a SharePoint Online document library with the below file URL.
https://contoso.sharepoint.com/sites/TestPTSite01/TestLibrary/TestFolder/test_file.txt
To retrieve information of this file, we need three parameters, site-id, drive-id of the library, and item-id of the file.
#Get Request
https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/items/{item-Id}
In this post, we will explore how to retrieve the site id, drive id, and item id from the server-relative URL of the file.
- Find Site Id by Site Name
- Find Site Id by Site Path
- Find Drive Id by Document Library name
- Find Item Id by File Path that Relative to Drive
Find Site Id by Site Name
We can use Search sites method to retrieve site details by site name. The mentioned file is located on the site “TestPTSite01”. The following request gets the site details and site id.
GET https://graph.microsoft.com/v1.0/sites?$search="TestPTSite01"
The site id is constructed with your SharePoint hostname (ex: contoso.sharepoint.com), Site Collection (SPSite) ID, and Site (SPWeb) ID. The Site (SPWeb) ID will point to the root site or sub-site in the given site collection.
Get https://graph.microsoft.com/v1.0/sites/{hostname},{spsite-id},{spweb-id}
If you want to point to the root site of a site collection, you can provide only the id of the site collection (SPSite).
Get https://graph.microsoft.com/v1.0/sites/{spsite-id}
Find Site Id by Site Path
The site can also be addressed by the path by using the SharePoint hostname, followed by a colon and the relative path to the site.
GET https://graph.microsoft.com/v1.0/sites/{hostname}:/{server-relative-path}
#Get site details
https://graph.microsoft.com/v1.0/sites/contoso.sharepoint.com:/sites/TestPTSite01
Find Drive Id by Document Library name
Once you got the site id, use the below Graph API Endpoint to get all the drives (Document Library) available on the site. You can match the library name and find the drive id of the library.
GET https://graph.microsoft.com/v1.0/sites/{site-id}/drives
Find Item Id by File Path that Relative to Drive
With the Site Id and Drive Id, we can easily find the drive item (List item) id by using the file path that is relative to the drive root (library).
#GET Request
https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/root:/{path-relative-to-root}
#Get file details
https://graph.microsoft.com/v1.0/sites/{site-id}/drives/{drive-id}/root:/TestFolder/test_file.txt