Fetch documents from SharePoint document library using Microsoft Graph API

Introduction

This article covers detailed insights on how you can fetch document/file details residing in a SharePoint document library using Microsoft Graph API. All the graph API calls in this article are performed at https://developer.microsoft.com/en-us/graph/graph-explorer.

Any developer can use the same graph API in the code solution of their choice, either in .NET, JavaScript/TypeScript, or any coding language.

Note. Make sure to register an app with the following API permissions whenever you add API to fetch the documents from the SharePoint document library in your code solution: Sites.Read.All, Sites.ReadWrite.All, Files.Read.All, Files.ReadWrite.All

For fetching documents from the SharePoint document library, I have divided this into 3 API calls to make it more dynamic so that anyone can consume this directly to their code solution.

  • Fetching Site ID based on the Site name

Navigate to Graph Explorer: https://developer.microsoft.com/en-us/graph/graph-explorer.

Sign in to Graph Explorer

  • Select GET and v1.0 then add this API- https://graph.microsoft.com/v1.0/sites/{tenantdomainname}.sharepoint.com:/sites/{sitename}
  • Replace tenantdomainname- Your tenant domain name
  • Replace sitename- Site name of the site where the document library resides

Fig 1.1 - GET Site ID API call

If your API call is correctly written, you will get 200 as API’s response with the details below.

Now, from the API response, fetch the value of parameter id; this is the site ID we will consume in the second step.

Fig 1.2 - Response of the GET Site ID API

  • Fetching document library (list) ID

Navigate to graph explorer and sign in

  • Select GET and v1.0, then add this API- https://graph.microsoft.com/v1.0/sites/{siteID}/lists?$filter=displayName+eq+'{LibraryName}'
  • Replace siteID- value fetched from the above API call
  • Replace LibraryName- Name of the library from which you wish to fetch the documents.

Fig 2.1 - API Response of the Fetch Document Library ID API call

If your API call is correctly written, you will get 200 as API’s response with the details as shown below

From the API response, grab the value of id from the value object (i.e., value.id will be your Document Library ID). This document library ID will be consumed as driveID in the next step

  • Using site ID and library/list ID to fetch documents

Navigate to graph explorer and sign in

  • Select GET, and v1.0, then add this API- https://graph.microsoft.com/v1.0/sites/{siteID} /drives/{driveID} /root/children
  • Replace siteID- from Step 1 API response
  • Replace driveID- from Step 2 API response

Fig 3.1 - Drive API response which will get all the documents details stored in the library

Summary

This article covers how to graph API can fetch document details from the SharePoint document library. I hope this was useful. Keep learning and Keep Sharing.