Search code examples
azuremicrosoft-graph-apisharepoint-onlinemicrosoft-graph-sdks

How to find a driveItem ID given only a document URL?


I need to be able to find a driveItem from the Microsoft Graph API, given only a document URL in this sort of format:

https://tenant.sharepoint.com/sites/somesite/somefolder/somedocument.doc

I know it is possible to do the opposite, e.g. get a document URL from a driveItem, but how do I get the driveItem when I only have a document URL?


Solution

  • You can use Search API, filter driveItem entity type, and specify the document URL in the queryString

    POST https://graph.microsoft.com/v1.0/search/query
    
    {
        "requests": [
            {
                "entityTypes": [
                    "driveItem"
                ],
                "query": {
                    "queryString": "path:\"https://tenant.sharepoint.com/sites/somesite/somefolder/somedocument.doc\""
                }
            }
        ]
    }
    

    The response will contain resource property with inner id which is driveItemId you need. The parentReference property contains additional details like driveId

    Another way is to get file by relative path, but it requires the knowledge of siteId and driveId related to the certain document library.

    GET https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/root:/somefolder/somedocument.doc:/