Search code examples
microsoft-graph-apisharepoint-onlinespfx

How can I get the siteId of the current site with Microsoft Graph API?


I can't find any ways to get the siteId of the site where I put the webpart in.

For example, my current site is at the https://{hostname}/sites/main1 which is not a root site, but I want to get siteId instead.

I tested my webpart in the https://{hostname}/sites/main1/_layouts/15/workbench.aspx URL.

From the site resource type documentation,

A site is identified by a unique ID that is a composite of the following values:

  • Site collection hostname (contoso.sharepoint.com)
  • Site collection unique ID (GUID)
  • Site unique ID (GUID)

How can I retrieve this information?

I am using JavaScript + React to build my webpart so I can get the hostname easily by using location.hostname but how to get the site-id easily with Graph API?


Solution

  • There is a test site, you can play with:

    https://graph.microsoft.com/v1.0/sites?search=test
    

    It returns with multiple constoso site. Get the ID from the site using this format:

    https://graph.microsoft.com/v1.0/sites/{hostname}:/sites/{path}?$select=id
    

    You can try this example on the Graph Explorer:

    https://graph.microsoft.com/v1.0/sites/m365x214355.sharepoint.com:/sites/contoso/Departments/Operations?$select=id
    

    You get back the ID in the {hostname},{spsite.id},{spweb.id} format. The result from the previous example:

    {
        "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites(id)/$entity",
        "id": "m365x214355.sharepoint.com,f66f0635-cbc1-4695-8c25-d76c20b5f883,d931d880-f421-44af-bb08-a8582011234f"
    }
    

    In this case, the site ID will be f66f0635-cbc1-4695-8c25-d76c20b5f883 value.

    For more information: