I want to work with SharePoint sites using Python. For now, I just want to ls on the site. I immediately ran into an issue where I need site id to do anything with it.
How do I get site id from the site name? I did retrieve it using powershell:
$uri = "https://graph.microsoft.com/v1.0/sites/"+$SharePointTenant+":/sites/"+$SiteName+"?$select=id"
$RestData1 = Invoke-MgGraphRequest -Method GET -Uri $uri -ContentType "application/json"
# Display Site ID
$RestData1.displayName
$RestData1.id
But now I want to perform the same operation as above but using msgraph library. The problem is I am not sure how to do it. So far I have:
import asyncio
from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient
tenant_id="..."
client_id="..."
client_secret="..."
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
scopes = ['https://graph.microsoft.com/.default']
client = GraphServiceClient(credentials=credential, scopes=scopes)
sharepoint_tenant = "foobar365.sharepoint.com"
site_name = "someTestSPsite"
site_id = "f482d14d-6bd1-1234-gega-3121183eb87a" # how do I get this using GraphServiceClient from the site_name ?
# so that I can do this
# this works with the id retrieved from PS script
drives = (asyncio.run(client.sites.by_site_id(site_id).drives.get()))
print(drives)
To get the Site ID from Site name and get Drives, modify the code like below:
import asyncio
from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient
from msgraph.generated.sites.sites_request_builder import SitesRequestBuilder
from kiota_abstractions.base_request_configuration import RequestConfiguration
tenant_id = "TenantID"
client_id = "ClientID"
client_secret = "Secret"
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
scopes = ['https://graph.microsoft.com/.default']
graph_client = GraphServiceClient(credential, scopes)
query_params = SitesRequestBuilder.SitesRequestBuilderGetQueryParameters(
search="RukSite",
request_configuration = RequestConfiguration(
query_parameters=query_params,
)
async def get_site_id():
result = await graph_client.sites.get(request_configuration=request_configuration)
site_id = result.value[0].id
return site_id
# Get the drives of the site by site_id
async def get_drives(site_id):
drives = await graph_client.sites.by_site_id(site_id).drives.get()
return drives
async def main():
site_id = await get_site_id()
# Print the Site ID
print(f"Site ID: {site_id}")
# Fetch the drives for the site using the site ID
drives = await get_drives(site_id)
# Print the drives
print(f"Drives: {drives}")
# Run the main async function
asyncio.run(main())
Make sure to assign Sites.Read.All
application type API permission.